How to convert a binary string to a byte array of 2 bytes in java

I have a binary string String A = "1000000110101110" . I want to convert this string to an array of bytes of length 2 in java

I used this link

I tried converting it to bytes in various ways.

  • I first converted this string to decimal, and then applied the code to be stored in an array of bytes

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

But get store values ​​in byte array are negative

 xByte[0] :-127 xByte[1] :-82 

Which are incorrect values.

2. I also tried using

 byte[] xByte = ByteBuffer.allocate(2).order(ByteOrder.BIG_ENDIAN).putInt(aInt).array(); 

But it throws an exception on the specified line, for example

  java.nio.Buffer.nextPutIndex(Buffer.java:519) at java.nio.HeapByteBuffer.putInt(HeapByteBuffer.java:366) at org.com.app.convert.generateTemplate(convert.java:266) 

What do I need to do now to convert a binary string into a 2 byte byte array? Is there a built-in function in java to get an array of bytes

+6
source share
4 answers

The answer you get

  xByte[0] :-127 xByte[1] :-82 

is correct.

This is called 2 compliments. 1st bit is used as a signed bit.

 0 for +ve 1 for -ve 

if the 1st bit is 0, than it calculates as regular. but if the 1st bit is 1, then it subtracts the values ​​of 7 bits from 128 and that someday the answer will be in the form of -ve.

In your case, the 1st value is 10000001 so 1 (1 bit) for -ve and 128-1 (last seven bits) = 127 so the value is -127

Read more about 2 submissions.

+2
source

try it

 String s = "1000000110101110"; int i = Integer.parseInt(s, 2); byte[] a = {(byte) ( i >> 8), (byte) i}; System.out.println(Arrays.toString(a)); System.out.print(Integer.toBinaryString(0xFF & a[0]) + " " + Integer.toBinaryString(0xFF & a[1])); 

Output

 [-127, -82] 10000001 10101110 

i.e. -127 == 0xb10000001 and -82 == 0xb10101110

+2
source

Use putShort to set a double-byte value. int has four bytes.

 // big endian is the default order byte[] xByte = ByteBuffer.allocate(2).putShort((short)aInt).array(); 

By the way, your first attempt is perfect. You cannot change the negative sign of bytes, since the most significant bit of these bytes is set. That which is always interpreted as a negative value.

10000001β‚‚ == -127

10101110β‚‚ == -82

+2
source

Bytes are signed with 8-bit integers. Thus, your result is completely correct. That is: 01111111 - 127, but 10,000,000 - -128. If you want to get numbers in the range 0-255, you need to use a larger variable type, for example short.

You can print the byte as unsigned as follows:

 public static String toString(byte b) { return String.valueOf(((short)b) & 0xFF); } 
+2
source

Source: https://habr.com/ru/post/954481/


All Articles