1

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?

1 Answer 1

3

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
Sign up to request clarification or add additional context in comments.

1 Comment

So, if you remove one zero from original string, it will become 6-byte.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.