I have binary string String A = "1000000110101110"
. I want to convert this string into byte array of length 2 in java
I have taken the help of this link
I have tried to convert it into byte by various ways
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);
But the values get store into the byte array are negative
xByte[0] :-127
xByte[1] :-82
Which are wrong values.
2.I have also tried using
byte[] xByte = ByteBuffer.allocate(2).order(ByteOrder.BIG_ENDIAN).putInt(aInt).array();
But it throws the exception at the above line like
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 should i do now to convert the binary string to byte array of 2 bytes?Is there any inbuilt function in java
to get the byte array
Bytes are signed 8 bit integers. As such your result is completely correct. That is: 01111111 is 127, but 10000000 is -128. If you want to get numbers in 0-255 range you need to use a bigger variable type like short.
You can print byte as unsigned like this:
try this
output
that is -127 == 0xb10000001 and -82 == 0xb10101110
Use
putShort
for putting a two byte value.int
has four bytes.By the way, your first attempt is perfect. You can’t change the negative sign of the bytes as the most significant bit of these bytes is set. That’s always interpreted as negative value.
10000001₂ == -127
10101110₂ == -82
The answer you are getting
is right.
This is called 2's compliment Represantation. 1st bit is used as signed bit.
if 1st bit is 0 than it calculates as regular. but if 1st bit is 1 than it deduct the values of 7 bit from 128 and what ever the answer is presented in -ve form.
In your case 1st value is
10000001
so 1(1st bit) for -ve and 128 - 1(last seven bits) = 127 so value is -127For more detail read 2's complement representation.