Question

The simple scenario: You have a byte array

byte[] message = { 1, 2, 3 };

To print it out in binary you can use the code:

for (byte b : message) {
    System.out.println(Integer.toBinaryString(0x100 + b).substring(1));
}

(Got that code from this stack overflow thread)

And get this output:

00000001
00000010
00000011



But if you tag a -128 on the end...

byte[] message = { 1, 2, 3, -128 };

00000001
00000010
00000011
0000000

WOAH! A seven digit binary number? I sense that this is something to do with two's complement, but the more I try to read on it, the more I get confused. I was expecting 10000000 to appear in the fourth line instead...

Can anyone explain why Integer.toBinaryString of -128 is seven digits in relatively simple terms?


Ye olde javadoc says The unsigned integer value is the argument plus 2^32 if the argument is negative; otherwise it is equal to the argument. This value is converted to a string of ASCII digits in binary (base 2) with no extra leading 0s. But like I said... just confuses me.



The context of this whole thing is that I'm trying out coding some of the SHA functions in java. Don't ask me why, I don't even know... I'm just curious/challenging myself/frustrating myself :)

The padding of a message for use in the SHA-256 function (making it a multiple of 512 in bit length) according to the documentation is the concatenation of:

  1. The original message
  2. A single 1 bit
  3. 0 bits up to the last 64 bits
  4. The original message length as a 64-bit value

Since my messages will most likely be in ASCII 8-bit codes, I simply need to tag a 10000000 in for #2... then I can just count the number of 0 BYTES to add in, I shouldn't have to plan for messages that aren't multiples of 8. The issue is making that 10000000.

Was it helpful?

Solution

(-128 + 0x100) =
(256 - 128) = 128 = 
0b10000000

Integer.toBinaryString(0b10000000) = "10000000"

"10000000".substring(1) = "0000000"

OTHER TIPS

There's a bug in the stack overflow thread you copied from. 0x100 is 256 in decimal, so...

0x100 + 1 = 257 = 0b100000001 (9 digits)
0x100 + (-128) = 128 = 0b10000000 (8 digits)

In other words, since 128 is less than Byte.MAX_VALUE, you don't get the padding effect that the poster intended. You can choose a bigger value to pad -- try 0x200 and strip the first two characters??

FWIW, it's understandable these types of bugs b/c negative byte values are a bit of a weird java thing. Oh well.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top