首页 文章

为什么AND数字在签名和未签名的演示文稿之间转换?

提问于
浏览
3

下面的代码显示一个以十六进制格式存储为Java字节值的数字,以及有符号和无符号表示形式 . 这可能不是正确的措辞 . 我的意思是,这些数字可以是C风格的1字节无符号字符值 . 如果我正在解释这些值(这里恰好是Java,但可能使用任何语言中的任何有符号类型),那么如果'number'溢出使用符号位,则数字将显示为负数 . 但是我可以通过ANDFF和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

2 回答

  • 8

    正如您所料, int 1的二进制文件是

    0000 0000 0000 0000 0000 0000 0000 0001
    

    根据二进制补码,你通过反转它并加1来否定一个数,所以二进制补码中签名 int -1的二进制看起来像

    1111 1111 1111 1111 1111 1111 1111 1111
    

    任何负数都将设置为高位,而任何正数都将具有高位0 .

    例如,0xff看起来像左边有一个长0字符串

    0000 0000 0000 0000 0000 0000 1111 1111
    

    虽然-0xff看起来像

    1111 1111 1111 1111 1111 1111 0000 0001
    

    使用 & 进行掩码时,只保留两者中的1位,因此-2和0xff看起来像

    1111 1111 1111 1111 1111 1111 1111 1110 |   -2
    0000 0000 0000 0000 0000 0000 1111 1111 | 0xff
    
    0000 0000 0000 0000 0000 0000 1111 1110 | -2 & 0xff = 0xfe
    

    使用正值进行AND运算会产生正值,因为结果高位始终为0 .

  • 2

    使用int第一个符号对一个字节进行AND运算 - 将该字节扩展为int,然后发生AND .

    这意味着,在这种情况下,字节被转换为具有符号扩展名的整数,但是已经选择了与AND的值,使得扩展符号位被屏蔽掉 .

    所以结果好像你对字节进行了零扩展 .

相关问题