我有二进制字符串String A = "1000000110101110".我想将此字符串转换为长度为2的字节数组java
我已经接受了这个链接的帮助
我试图通过各种方式将其转换为字节
我先将该字符串转换为十进制,然后将代码应用于存储到字节数组中
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);
Run Code Online (Sandbox Code Playgroud)但是存储到字节数组中的值是负数
xByte[0] :-127
xByte[1] :-82
Run Code Online (Sandbox Code Playgroud)
哪个是错误的值.
我也试过用
byte[] xByte = ByteBuffer.allocate(2).order(ByteOrder.BIG_ENDIAN).putInt(aInt).array();
Run Code Online (Sandbox Code Playgroud)
但它会在上面的行中引发异常
java.nio.Buffer.nextPutIndex(Buffer.java:519) at
java.nio.HeapByteBuffer.putInt(HeapByteBuffer.java:366) at
org.com.app.convert.generateTemplate(convert.java:266)
Run Code Online (Sandbox Code Playgroud)
我现在该怎么做才能将二进制字符串转换为2字节的字节数组?是否有任何内置函数java来获取字节数组