TonyW
TonyW

Reputation: 18875

Java: the length of the byte array seems to be wrong from converting a string of binary

I am trying to do bits padding to a byte array, and the number of bits that I need to pad is 48 (so 6 bytes). Below is the binary string:

String paddingBinaryString = "100000000000000000000000000000000000000000000000"

However, the byte array from this binary string shows the length to be 7 (instead of 6!). The way I convert the 48-bit binary String to byte array is:

byte[] paddingByteArr = new BigInteger(paddingBinaryString, 2).toByteArray();
System.out.println("paddingByteArr.length: " + paddingByteArr.length); //shows 7

There must be something obviously wrong, because 48 bits must be 6 bytes, not 7, right?

Upvotes: 1

Views: 645

Answers (1)

Paul Boddington
Paul Boddington

Reputation: 37645

The documentation for toByteArray says

The array will contain the minimum number of bytes required to represent this BigInteger, including at least one sign bit

The number is positive so at least one extra zero has to be added at the beginning, requiring a whole extra byte. The representation is big endian, so the resulting array is

00000000 10000000 00000000 00000000 00000000 00000000 00000000 
       ^
       |
       *--- sign bit

Upvotes: 3

Related Questions