gpt4 book ai didi

java - 为什么位或操作会导致符号扩展而位却不会?

转载 作者:行者123 更新时间:2023-11-29 05:33:34 24 4
gpt4 key购买 nike

我需要在 Java 中将一个字节转换为 int,但我不想进行符号扩展,所以我做了

byte b = -1
(int) (b & 0xF) // this returns 15, which is what I want
(int) (b | 0) // this returns -1, which is essentially 0xFFFF, sign extension happens, not what I want

我认为以上两个应该给出相同的结果,但事实并非如此。我一定在位操作中遗漏了一些东西。

最佳答案

诀窍是打印这些值的二进制表示并对它们执行二进制操作

byte b = -1;
int a = (int) (b & 0xF); // this returns 15, which is what I want
int c = (int) (b | 0); // this returns -1, which is essentially 0xFFFF
System.out.println("b:" + Integer.toBinaryString(b));
System.out.println("a:" + Integer.toBinaryString(a));
System.out.println("c:" + Integer.toBinaryString(c));
System.out.println("0xF:" + Integer.toBinaryString(0xF));

打印

b:11111111111111111111111111111111
a:1111
c:11111111111111111111111111111111
0xF:1111

所以 b & OxF

11111111111111111111111111111111
00000000000000000000000000001111 (AND)
--------------------------------
1111 (15)

b | 0

11111111111111111111111111111111
00000000000000000000000000000000 (OR)
--------------------------------
11111111111111111111111111111111 (-1)

Hot Licks explains why the byte value -1 is represented in binary as it is.

关于java - 为什么位或操作会导致符号扩展而位却不会?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20278093/

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