Java Binary Convert to binaryString2ByteArr(String binary)

Here you can find the source of binaryString2ByteArr(String binary)

Description

binary String Byte Arr

License

Open Source License

Declaration

public static byte[] binaryString2ByteArr(String binary) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

public class Main {

    public static byte[] binaryString2ByteArr(String binary) {
        StringBuffer str = new StringBuffer();
        StringBuffer temp = new StringBuffer();
        int length = binary.length();
        str.append(binary);/*from  w  w w .  j ava 2 s .  c o  m*/
        byte[] result = null;
        if (length >= 8 && (length % 8 == 0)) {
            result = new byte[length / 8];
        } else {
            int zero = (((length / 8) + 1) * 8) - length;
            for (int i = 0; i < zero; i++) {
                str.append("0");
            }
            result = new byte[length / 8 + 1];
        }

        int tempVar = 0;
        int r = 0;
        for (int i = 0; i < str.length(); i++) {
            temp.append(str.charAt(i));
            if ((i + 1) % 8 == 0) {
                r = ((i + 1) / 8) - 1;
                String eight = temp.toString();
                tempVar = Integer.parseInt(eight, 2);
                byte var = (byte) tempVar;
                result[r] = var;
                temp.delete(0, temp.length());
            }
        }
        return result;
    }
}

Related

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