2

I am putting different binary numbers into a byte array. One of the numbers are: 10001101010010010000000000001000 this number is giving me a NumberFormatException on the line where I try to parse it, obviously because it's too big. See code below where string is the binary number.

int number = Integer.parseInt(string, 2);
ByteBuffer bytes = ByteBuffer.allocate(4).putInt(number);
byte[] byteInstruction = bytes.array();

What I want is to put the numbers in my byte array but as they are 32-bit numbers I don't want to take up more than 4 bytes in my array. When I use long to parse it works but then I take up 8 spaces in my byte array.

long number = Long.parseLong(string, 2);
ByteBuffer bytes = ByteBuffer.allocate(8).putLong(number);
byte[] byteInstruction = bytes.array();

If I print out the array later I get this:

[0, 0, 0, 0, -115, 73, 0, 8]

where we can see that there are 4 spots free. How can I solve this? How did I mess up? All help is appreciated.

Fjodor
  • 529
  • 1
  • 7
  • 19

1 Answers1

1

Your input string "10001101010010010000000000001000" represents value that is too big for signed Integer. Integer.MAX_VALUE = 2147483647 and the input string you've passed has a value of 2370371592.

The Integer.parseInt does not interpret the leading 1 at position 32 from right as sign. If you would like parse a negative value it would have to be preceded with - sign.

See this answer for more through explanation.

If you expect the input "10001101010010010000000000001000" to in fact mean "-0001101010010010000000000001000" just replace the first character with +/- depending on the value of 32 bit from right.

Alternatively if you would like to treat the binary string in Two's complement compatible way you can use approach from this answer:

int msb = Integer.parseInt("1000110101001001", 2);
int lsb = Integer.parseInt("0000000000001000", 2);

int result = msb<<16 | lsb;
Community
  • 1
  • 1
miensol
  • 39,733
  • 7
  • 116
  • 112