How are negative numbers represented in 32-bit signed integer?

后端 未结 7 1876
时光取名叫无心
时光取名叫无心 2020-12-02 01:30

How are negative number represented in 32-bit signed integer? Is it two\'s or one\'s complement? or the last bit on the left is like a flag? For example: (-10)

7条回答
  •  青春惊慌失措
    2020-12-02 02:08

    Just for reference: negation -> adding one.

    Take 5 as an example in 8 bits, quoted from wiki

    to convert 5 to -5: 0000 0101 - flip -> 1111 1010 - add one -> 1111 1011
    

    There is a trick to convert a number from positive to negative or vice verse:

    Adding them ignoring their signed bit (the leftmost bit) will give you 2^N (where N is the amount of the bits to represent the number).

    As the example above in 8-bit representation the sum of 5 (0000 0101) and -5 (1111 1011) will give you 1 0000 0000 which is (2 ^ 8).

提交回复
热议问题