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:
- The original message
- A single
1
bit 0
bits up to the last 64 bits- 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
.