我有一个二进制字符串String A = "1000000110101110"
,我想将该字符串转换成长度为2的字节数组在Java
中。
我参考了这个链接的帮助。
我尝试了各种方法将其转换为字节。
I have converted that string into decimal first and then apply the code to store into the byte array
int aInt = Integer.parseInt(A, 2); byte[] xByte = new byte[2]; xByte[0] = (byte) ((aInt >> 8) & 0XFF); xByte[1] = (byte) (aInt & 0XFF); System.arraycopy(xByte, 0, record, 0, xByte.length);
但是存储在字节数组中的值是负数
xByte[0] :-127
xByte[1] :-82
这些是错误的值。
2.我也尝试使用
byte[] xByte = ByteBuffer.allocate(2).order(ByteOrder.BIG_ENDIAN).putInt(aInt).array();
但是它在上面的那一行抛出了异常,如下所示:
java.nio.Buffer.nextPutIndex(Buffer.java:519) at
java.nio.HeapByteBuffer.putInt(HeapByteBuffer.java:366) at
org.com.app.convert.generateTemplate(convert.java:266)
现在我应该怎么样将二进制字符串转换为两个字节的字节数组?Java
中是否有任何内置函数可以获取字节数组?
byte[] xByte = {(byte) ( aInt >> 8), (byte) aInt};
但是存储在第零个位置的值仍然是负数xByte[0] :-127
。 - rachana