问题
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?
回答1:
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.)
回答2:
A byte is a signed quantity ranging from -128 to +127. It wraps around to the lowest negative once it reaches 127.
回答3:
Because it doesn't fit in the range of byte . The range of byte
is from -128 to +127 . The byte data type is an 8-bit signed two's complement integer. It has a minimum value of -128 and a maximum value of 127 (inclusive) From the JLS 4.2.1:
For byte, from -128 to 127, inclusive
Hence the value 128
is actually -128
in byte
.
回答4:
That's because a byte can only store 8 bits of information, which is 2^8 = 256 values, 128 negative, zero, and 127 positive, and it wraps around. Use int
instead if you need to go up to 256, otherwise count from -127 to 128 with your byte if memory use is important.
来源:https://stackoverflow.com/questions/17483243/my-byte-suddenly-becomes-a-negative-number-and-count-down