如何创建十六进制补码?



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

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
}

按位否定运算符 ~[Refer:https://docstore.mik.ua/orelly/java/langref/ch04_04.htm]

按位否定运算符 (~( 可能显示为一元表达式的一部分。~ 运算符的操作数类型必须是整数数据类型,否则会发生编译时错误。~ 运算符可以在执行计算之前执行类型转换。如果操作数的类型为字节、短整型或字符,则运算符在生成值之前将其操作数转换为 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: %dn", (int)a, (int)a);
System.out.printf(">>>>>b HexaDecimal: %x Decimal: %dn", (int)b, (int)b);
System.out.printf(">>>>>~a HexaDecimal: %x Decimal: %dn", ~a, ~a);
System.out.printf(">>>>>~b HexaDecimal: %x Decimal: %dn", ~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 中的按位编译确实应用了一元提升,其中 "char" 操作数被提升为 int . https://docs.oracle.com/javase/specs/jls/se7/html/jls-5.html#jls-5.6.2

Java int 是一个 4 字节的 SIGNED 类型,因此你会看到区别。

~buffer[0]=11111111111111111111111111111111  is correct
~buffer[0]=11111111  is incorrect

最新更新