In binary, MAX_VALUE
s for each type start with a 0
bit and continue with all 1
bits. That means, to get Integer.MAX_VALUE
, you'll need a 0
bit followed by 31 1
bits:
Integer.MAX_VALUE: 01111111111111111111111111111111
However, you're not producing that. You're using Byte.MAX_VALUE
repeated four times. This means you have a 0
bit followed by seven 1
bits followed by a 0
bit followed by seven 1
bits and so on:
Byte.MAX_VALUE: 01111111
Byte.MAX_VALUE×4: 01111111011111110111111101111111 (2,139,062,143)
Since -1
s are composed solely of 1
bits, you can get what you want with one Byte.MAX_VALUE
followed by three -1
s:
Byte.MAX_VALUE: 01111111
-1: 11111111
Byte.MAX_VALUE, -1×3: 01111111111111111111111111111111
A second problem will arise when you try to combine these. When Java converts a negative byte
to an int
, it becomes a negative int
, which means a whole lot of 1
s are added to the left side of it in binary. Thus, you'll need to use & 0xff
(or Byte.toUnsignedInt
) to strip those added bits from each byte
.
It's also better to use |
instead of +
, because it fits the meaning of what's going on more precisely.
So, to produce Integer.MAX_VALUE
:
byte a = Byte.MAX_VALUE;
byte b = -1;
byte c = -1;
byte d = -1;
System.out.println(((a & 0xff) << 24) | ((b & 0xff) << 16) | ((c & 0xff) << 8) | ((d & 0xff) << 0));