Java Binary Convert to binaryStringToBytes(String binaryString)

Here you can find the source of binaryStringToBytes(String binaryString)

Description

binary String To Bytes

License

Apache License

Declaration

public static byte[] binaryStringToBytes(String binaryString) 

Method Source Code

//package com.java2s;
/**/*www. j a  v a  2  s.  com*/
 *  Copyright 2015 Groupon
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

public class Main {
    public static byte[] binaryStringToBytes(String binaryString) {
        byte[] bytes = new byte[(int) Math
                .ceil(binaryString.length() / 8.0)];
        for (int i = 0, j = 0, k = 7; i < binaryString.length(); i++) {
            byte bit = (byte) (binaryString.charAt(i) - '0');
            bytes[j] = (byte) (bytes[j] | bit << k);
            if (k == 0) {
                j++;
                k = 7;
            } else {
                k--;
            }
        }
        return bytes;
    }
}

Related

  1. binaryString(byte aByte, boolean prefix)
  2. binaryString2ByteArr(String binary)
  3. binaryString2Long(String binString)
  4. binaryStringToFloat(String value)