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

时间:2015-12-01 10:35:51

标签: java android binary byte

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

二进制字符串

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

3 个答案:

答案 0 :(得分:0)

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

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

答案 1 :(得分:0)

您可以通过自己转换来“手动”执行此操作

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);

答案 2 :(得分:0)

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

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