我的字节突然变成负数并递减计数 [英] My byte suddenly becomes a negative number and count down
问题描述
我有一些代码,每次通过循环时,它会将字节增加8位。
一切都按预期进行,直到我达到120,然后我的数字突然变为负数。
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.
代码:
byte b = 0;
for(int i = 0; i < 0x100; i += 8) {
System.out.print(b + " ");
b += 8;
}
输出:
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
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
我想看的东西:
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
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
有人知道为什么它在120后开始递减计数而不是增加到256吗?
Does anyone know why it starts counting down after 120 instead of going up to 256?
推荐答案
有人知道为什么它会在120点后开始倒数而不是增加到256点吗?
Does anyone know why it starts counting down after 120 instead of going up to 256?
是的。 Java字节已签名-就是这么简单。从第4.2.1节JLS :
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:
- 对于字节,从-128到127(包括端值)
- ...
将字节值显示为无符号的最简单方法是将其提升为 int
并使用0xff对其进行屏蔽:
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) + " ");
这篇关于我的字节突然变成负数并递减计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!