下面的代码显示了一个存储为十六进制的 Java 字节值的数字,并以有符号和无符号表示。这可能不是正确的措辞。我的意思是,这些数字可能是 C 风格的 1 字节无符号字符值。如果我正在解释这些值(这里恰好是 Java,但可以在任何语言中使用任何有符号类型),那么如果“数字”溢出到使用符号位,那么数字将显示为负数。但是我可以通过 ANDing 与 0xFF 以无符号解释的形式打印。
我了解 AND 的工作原理,但我不明白 ANDing 如何呈现为未签名。有人可以解释一下吗?
public class understand_casting {
public static String printbinary(byte val) {
int displayMask = 1 << 7;
String str = new String();
for(int bit = 1; bit <= 8; ++bit) {
str += (val & displayMask) == 0 ? '0' : '1';
val <<= 1; //shift one to left
}
return str;
}
public static void main(String[] args) {
System.out.printf("0x50=%s, as int=%d, as unsigned int=%d\n", printbinary((byte)0x50), (byte)0x50, ((byte)0x50 & 0xFF));
System.out.printf("0x88=%s, as int=%d, as unsigned int=%d\n", printbinary((byte)0x88),(byte)0x88, ((byte)0x88 & 0xFF));
System.out.printf("0x3E=%s, as int=%d, as unsigned int=%d\n", printbinary((byte)0x3E),(byte)0x3E, ((byte)0x3E & 0xFF));
System.out.printf("0xB7=%s, as int=%d, as unsigned int=%d\n", printbinary((byte)0xB7), (byte)0xB7, ((byte)0xB7 & 0xFF));
}
}
我得到这个输出:
0x50=01010000, as int=80, as unsigned int=80
0x88=10001000, as int=-120, as unsigned int=136
0x3E=00111110, as int=62, as unsigned int=62
0xB7=10110111, as int=-73, as unsigned int=183