冒着接下来几天感到羞耻的风险......请向我解释以下内容。
我需要对带有字节的整数进行算术运算。
int a = 0x0100;
byte b = (byte)0xff;
int c = a | b;
我期望 c 为 0x100 | 0xff = 0x1ff = 511
。
但它是0xffffffff = -1
为什么?
最佳答案
b
是 -1
。
当你做a | b
,b
被提升为 int,仍然是 -1
。
15.22.1. Integer Bitwise Operators &, ^, and |
When both operands of an operator &, ^, or |
are of a type that is convertible (§5.1.8) to a primitive integral type,
binary numeric promotion is first performed on the operands (§5.6.2).
因此,a | b
的计算方式就像 a | -1
.
final int a = 0x0100;
final int b = 0xFF;
final int c = a | b;
我不确定你到底想做什么,但是。
How could I accomplish adding 8 bits to the end of a int value in simple steps?
int appendDummyOnes(final int value, final int size) {
return (value << size) | (-1 >>> (Integer.SIZE - size));
}
int remarkDummyOnes(final int value, final int size) {
return value | (-1 >>> (Integer.SIZE - size));
}
关于Java OR 运算符发疯了,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32631424/