只需使用Apache Commons 的BinaryCodec:
byte[] bytes = new BinaryCodec().toByteArray("1000000111010000");
如果您想自己进行此类转换,您的代码需要进行一些更正。
您期望A.charAt(i)
它将返回数字 0 或 1,但实际上会返回char
“0”或“1”。char 数据类型是单个 16 位 Unicode 字符,数值范围从 0 到 2^16,它的值正式称为 代码点。
要打印代码点值,您需要将 char 转换为 int:
System.out.println("Character " + A.charAt(i) + " has a code point numeric value of " + (int)A.charAt(i));
“0”和“1”的输出:
Character 0 has a code point numeric value of 48
Character 1 has a code point numeric value of 49
运算符 '<<'将char 操作数转换为 int,因此这种转换会产生错误的结果,因为:
firstByte = (byte) (firstByte | (A.charAt(i) << i));
是相同的
firstByte = (byte) (firstByte | ( (int)A.charAt(i) << i));
这对于 char '0' 与将值 48 向左移动相同:
firstByte = (byte) (firstByte | ( 48 << i));
要将 char '0' 或 '1' 转换为 0 或 1 数值,请使用 Character.getNumericValue(A.charAt(i)):
firstByte = (byte) (firstByte | ( Character.getNumericValue(A.charAt(i)) << i));
按价值转移i
也是不正确的。您需要移动(7-i)
第一个字节或(7-i%8)
第二个字节。当 indexi
达到 8 时,它需要从 0 开始计数,因此i%8
打印字节类型的值时,您有两种选择:字节数值或二进制字符串表示:
System.out.println("FIRST byte numeric value = " + xByte[0] + ", binary string representation = " + Integer.toBinaryString((xByte[0]+256)%256));
System.out.println("SECOND byte numeric value = " + xByte[1] + ", binary string representation = " + Integer.toBinaryString((xByte[1]+256)%256));
输出:
FIRST byte value = -127, binary representation = 10000001
SECOND byte value = -48, binary representation = 11010000
整个更正示例:
public class ByteTest
{
public static void main(String[] args)
{
byte firstByte=0;
byte secondByte=0;
String A = "1000000111010000";
byte[] xByte = new byte[2];
for(int i=0 ; i<A.length() ;i++){
System.out.println("Character " + A.charAt(i) + " has a code point numeric value of " + (int)A.charAt(i));
if(i<8){
System.out.println(" i : "+i+" A.char[i] :"+A.charAt(i));
firstByte = (byte) (firstByte | (Character.getNumericValue(A.charAt(i)) << (7-i)));
}else{
System.out.println(" i : "+i+" A.char[i] :"+A.charAt(i));
secondByte = (byte) (secondByte | (Character.getNumericValue(A.charAt(i)) << (7-i%8)));
}
}
xByte[0] = firstByte;
xByte[1] = secondByte;
System.out.println("FIRST byte numeric value = " + xByte[0] + ", binary string representation = " + Integer.toBinaryString((xByte[0]+256)%256));
System.out.println("SECOND byte numeric value = " + xByte[1] + ", binary string representation = " + Integer.toBinaryString((xByte[1]+256)%256));
}
}