简体   繁体   English

带符号字节的按位AND运算

[英]Bitwise AND operation with a signed byte

Here is the code: 这是代码:

int i = 200;
byte b = (byte) 200;
System.out.println(b);
System.out.println((short) (b));
System.out.println((b & 0xff));
System.out.println((short) (b & 0xff));

Here is the output: 这是输出:

-56
-56
200
200

Bitwise AND with 0xff shouldn't have changed anything in b , but apparently it does have an effect, why? 按位AND与0xff不应该改变b任何内容,但显然它确实有效,为什么?

It has an effect because 200 is beyond the maximum possible (signed) byte , 127 . 它有效,因为200超出了最大可能(带符号) byte 127 The value is already assigned -56 because of this overflow. 由于此溢出,该值已分配-56 The most significant byte, worth -128 , is set. 设置了最重要的字节,值为-128

11001000

The first 2 output statements show -56 because of this, and the fact that casting to a short will perform sign extension to preserve negative values. 因此,前两个输出语句显示-56 ,并且转换为short将执行符号扩展以保留负值。

When you perform & 0xff , 2 things happen. 当你执行& 0xff ,会发生两件事。 First, the value is promoted to an int , with sign extension. 首先,将值提升为带符号扩展名的int

11111111 11111111 11111111 11001000

Then, the bit-and is performed, keeping only the last 8 bits. 然后,执行bit-and,仅保留最后8位。 Here, the 8th bit is no longer -128 , but 128 , so 200 is restored. 这里,第8位不再是-128 ,而是128 ,因此恢复了200

00000000 00000000 00000000 11001000

This occurs whether the value is casted to a short or not; 无论价值是否变为short发生这种情况; a short has 16 bits and can easily represent 200 . short有16位,可以很容易地代表200

00000000 11001000

Java byte is a signed type. Java byte是带符号的类型。 That is why you see a negative number when you print it: 200, or 0xC8 , is above the largest positive number representable by byte , so it gets interpreted as a negative byte . 这就是为什么在打印时看到负数的原因:200或0xC8高于可由byte表示的最大正数,因此它被解释为负byte

However, 0xff constant is an int . 但是, 0xff常量是一个int When you perform arithmetic and bitwise logic operations on a byte and an int * , the result becomes an int . byteint *执行算术和按位逻辑运算时,结果变为int That is why you see 200 printed in the second set of examples: (b & 0xff) produces an integer 200 , which remains 200 after shrinking conversion to short , because 200 fits into a short without becoming negative. 这就是为什么你在第二组例子中看到200打印的原因: (b & 0xff)产生一个整数200 ,在缩小转换为short之后仍为200 ,因为200适合于一个short而不变为负数。

* or another byte , for that matter; *或其他byte ,就此而言; Java standard specifies a list of conversions that get applied depending on operand types. Java标准指定了根据操作数类型应用的转换列表。

working with different integer types is a mine field. 使用不同的整数类型是一个雷区。

for example, what's going on here? 例如,这里发生了什么?

byte b = (byte) 200;

it's actually equivalent to 它实际上相当于

int i = 200;
byte b = (byte)i;

and the narrowing cast (byte) simply takes the lowest 8 bits of the int value. 并且缩小的强制转换(byte)只占用int值的最低8位。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM