Android : 将二进制字符串转换为字节

Android : convert binary string to byte

正如标题所说,我必须将二进制字符串转换为字节格式。我的二进制字符串只包含 6 位数据。我需要将这个 6 位二进制字符串转换为字节值

二进制字符串

String s1 =  "111011";
String s2 =  "111000";
String s3 =  "000000";
String s4 =  "111000";
String s5 =  "110111";

尝试使用基数为 2 的 Byte.parseByte() - Javadoc:

byte b = Byte.parseByte(s1, 2);

你可以"manually"自己转换

byte b = 0, pot = 1;
for (int i = 5; i >= 0; i--) {
    // -48: the character '0' is No. 48 in ASCII table,
    // so substracting 48 from it will result in the int value 0!
    b += (str.charAt(i)-48) * pot;
    pot <<= 1;    // equals pot *= 2 (to create the multiples of 2 (1,2,3,8,16,32)
}

这会将这些位乘以 (1, 2, 4, 8, 16, 32) 以确定生成的十进制数。

另一种可能是真正手动将 6 位二进制数字计算为十进制值:

byte b = (byte)
    ((str.charAt(5) - '0') * 1 +
    (str.charAt(4) - '0') * 2 + 
    (str.charAt(3) - '0') * 4 + 
    (str.charAt(2) - '0') * 8 + 
    (str.charAt(1) - '0') * 16 + 
    (str.charAt(0) - '0') * 32);

您需要一个实际的字节,还是正在寻找一个整数?

String s = "101";
System.out.println(Integer.parseInt(s,2));