gpt4 book ai didi

java - 如何创建十六进制补码?

转载 作者:行者123 更新时间:2023-11-30 02:08:17 30 4
gpt4 key购买 nike

我有十六进制值,想要创建按位补码。例如:

0x00 -> 0xFF
0xC4 -> 0x3B

以下测试失败,但为什么?

@Test
public void testBitwiseComplement() {
char[] buffer = new char[] {0x00, 0xff};
assertEquals(buffer[0], ~buffer[1]); //expected 0, but was -256
assertEquals(buffer[1], ~buffer[0]); //expected 255, but was -1
}

最佳答案

按位求反运算符~[引用:https://docstore.mik.ua/orelly/java/langref/ch04_04.htm]

按位否定运算符 (~) 可以作为一元表达式的一部分出现。 ~ 运算符的操作数类型必须是整数数据类型,否则会出现编译时错误。 ~ 运算符可以在执行计算之前执行类型转换。如果操作数的类型是 byte、short 或 char,则运算符在生成值之前会将其操作数转换为 int。否则 ~ 运算符会生成与其操作数相同类型的值。

public class BitwiseNegation {

public static void main(String args[]) throws Exception {
char a = 0xff;
char b = 0x00 ;

System.out.printf(">>>>>a HexaDecimal: %x Decimal: %d\n", (int)a, (int)a);
System.out.printf(">>>>>b HexaDecimal: %x Decimal: %d\n", (int)b, (int)b);

System.out.printf(">>>>>~a HexaDecimal: %x Decimal: %d\n", ~a, ~a);
System.out.printf(">>>>>~b HexaDecimal: %x Decimal: %d\n", ~b, ~b);
}

}

输出:

>>>>>a HexaDecimal: ff Decimal: 255   
>>>>>b HexaDecimal: 0 Decimal: 0
>>>>>~a HexaDecimal: ffffff00 Decimal: -256
>>>>>~b HexaDecimal: ffffffff Decimal: -1

由于一元运算符将 char 提升为 int,因此值 0xff 变为 0x000000ff,按位补码后变为 0xffffff00。现在这个数字是一个负数(符号位是1),通过反转二进制补码表示,该数字变成-256。但0x00的按位补码是-1。因此断言失败。

因此,仅对于值 0xffffffff 和 0x00000000,它们的按位补码也相等。

关于java - 如何创建十六进制补码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50858313/

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