问题描述
对于0xff,不按位进行AND运算本质上意味着返回相同的值,就此而言,在此代码中?
Doesn't bitwise-ANDing with 0xff essentially mean getting the same value back, for that matter, in this code?
byte[] packet = reader.readPacket();
short sh;
sh = packet[1];
sh &= 0xFF;
System.out.print(sh+" ");
奇怪的是,如果不包括ANDing,我会得到-1,但如果包含了255,可能会有人解释原因是什么?
Weirdly, I get a -1 if that ANDing is not included but a 255 when included Could someone explain the reason?
正如我所看到的,0xff只是1111 1111.不是吗?
As I see it 0xff is just 1111 1111. Isn't it?
推荐答案
是的, 0xff
只是 1111 1111
。但这是尝试显示无符号字节值,即使在Java byte
中已签名。对于签名的字节
,值 0xff
为 -1
,但是 255
在短
中。
Yes, 0xff
is just 1111 1111
. But this is attempting to display the unsigned byte value, even though in Java byte
s are signed. The value 0xff
is -1
for a signed byte
, but it's 255
in a short
.
当a读取 byte
0xff
的值,打印该值将产生 -1
。所以它分配给短
,它有更大的范围并且可以存储 byte
值,这些值通常会溢出为负值数字作为字节
作为正整数,例如144作为字节
是 0x90
,或-112,但它可以正确存储为 144
作为短
。
When a byte
value of 0xff
is read, printing the value would yield -1
. So it's assigned to a short
which has a bigger range and can store byte
values that would normally overflow to be a negative number as a byte
as a positive integer, e.g. 144 as a byte
is 0x90
, or -112, but it can be properly stored as 144
as a short
.
所以字节
-1
的值分配给 short
。但这又做了什么?进行原始扩展转换,并对负值进行符号扩展。所以 1111 1111
变成 11111111 11111111
,仍然 -1
,但这次是短
。
So the byte
value of -1
is assigned to a short
. But what does that do? A primitive widening conversion takes place, and negative values are sign-extended. So 1111 1111
becomes 11111111 11111111
, still -1
, but this time as a short
.
然后位掩码 0xff
( 00000000 11111111
)用于再次输出最后8位:
Then the bitmask 0xff
(00000000 11111111
) is used to get the last 8 bits out again:
-1: 11111111 1111111
0xFF: 00000000 1111111
======================
255: 00000000 1111111
这只是一种获得无符号字节的方法
value,将其转换为 short
,然后屏蔽字节
中的原始位,将其显示为无符号值。
It's just a way to get the unsigned byte
value, by converting it to short
and then masking out the original bits from the byte
, to display it as an unsigned value.
这篇关于与0xff进行逐位AND运算很重要?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!