gpt4 book ai didi

Java OR 运算符变得疯狂

转载 作者:行者123 更新时间:2023-11-30 06:12:38 25 4
gpt4 key购买 nike

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

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com