I have some code that increases a byte by 8 bits every time it passes through my loop. It all goes as expected until I hit 120, then my numbers suddenly become negative.
Code:
byte b = 0;
for(int i = 0; i < 0x100; i += 8) {
System.out.print(b + " ");
b += 8;
}
Output:
0 8 16 24 32 40 48 56 64 72 80 88 96 104 112 120 -128 -120 -112 -104 -96 -88 -80 -72 -64 -56 -48 -40 -32 -24 -16 -8
What I want to see:
0 8 16 24 32 40 48 56 64 72 80 88 96 104 112 120 128 136 144 152 160 168 176 184 192 200 208 216 224 232 240 248 256
Does anyone know why it starts counting down after 120 instead of going up to 256?
In C#, a byte represents an unsigned 8-bit integer, and can therefore not hold a negative value (valid values range from 0 to 255 ).
Negative Numbers. Because Byte is an unsigned type, it cannot represent a negative number.
In Java, byte is an 8-bit signed (positive and negative) data type, values from -128 (-2^7) to 127 (2^7-1) . For unsigned byte , the allowed values are from 0 to 255 .
A byte can't be -1. A byte can only store numbers between 0 and 255 inclusive. Depending on the range of your numbers you could use a char (-128 to +127) or an int (-32768 to +32767). Save this answer.
Does anyone know why it starts counting down after 120 instead of going up to 256?
Yes. Java bytes are signed - it's as simple as that. From section 4.2.1 of the JLS:
The values of the integral types are integers in the following ranges:
- For byte, from -128 to 127, inclusive
- ...
The easiest way to display a byte value as if it were unsigned is to promote it to int
and mask it with 0xff:
System.out.print((b & 0xff) + " ");
(The &
operator will perform binary numeric promotion automatically.)
A byte is a signed quantity ranging from -128 to +127. It wraps around to the lowest negative once it reaches 127.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With