Java OR 运算符发疯了

标签 java operator-keyword

冒着接下来几天感到羞耻的风险......请向我解释以下内容。
我需要对带有字节的整数进行算术运算。

int a = 0x0100;
byte b = (byte)0xff;
int c = a | b;

我期望 c 为 0x100 | 0xff = 0x1ff = 511
但它是0xffffffff = -1 为什么?

最佳答案

b-1。 当你做a | bb 被提升为 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/

相关文章:

c# - 无绑定(bind)操作信息异常

java - 如何在 yarn 中从主机名或节点ID到达节点标签?

java - 使用 AES/CTR 模拟流密码

下标运算符的 C++ 继承规则

c# - 对方法返回值使用 C# 丢弃运算符是否有意义?

java - Spring Boot 替代索引页

java - 如何禁用 Wildfly 10 中的计时器服务?

javascript - 为什么 1 & 1 === 1 返回 true 而 2 & 2 === 2 返回 false?

c++ - 重载 operator<< 改变成员变量

c++ - 非成员(member)运营商作为外国类(class)的私有(private)成员(member)