Binary presentation of negative integer in Java

后端 未结 5 2000
予麋鹿
予麋鹿 2020-12-03 22:30

Please, help me to understand binary presentation of negative integers.

For example we have 5. Binary presentation of 5 is 00000000.00000000.00000000.00000101

5条回答
  •  自闭症患者
    2020-12-03 23:29

    Here is an example for 2's compliment:

    If you have -30, and want to represent it in 2's complement, you take the binary representation of 30:

    0000 0000 0000 0000 0000 0000 0001 1110

    Invert the digits.

    1111 1111 1111 1111 1111 1111 1110 0001

    And add one.

    1111 1111 1111 1111 1111 1111 1110 0010

    Converted back into hex, this is 0xFFFFFFE2. And indeed, suppose you have this code:

    #include 
    
    int main() {
        int myInt;
        myInt = 0xFFFFFFE2;
        printf("%d\n",myInt);
    
        return 0;
    }
    

    That should yield an output of -30. Try it out if you like.

提交回复
热议问题