How to know if a binary integral number represents a negative number?

前端 未结 5 440
别那么骄傲
别那么骄傲 2021-02-04 00:06

I am reading some C text. In the Negative and Positive Values session, the author mentioned several ways of representing a negative number in binary form.

I understood a

5条回答
  •  北恋
    北恋 (楼主)
    2021-02-04 00:41

    For example, the (number) -92 has the binary form: 10100100 (in an 8 bit byte representation) . But if we are given 10100100, can we say that is -92, and not other non-negative number?

    No, you will need to know in advance whether a signed or unsigned representation / convention was used, and even if you know it is signed, then you will also need to know the encoding used to store the number.

    If the 8-bit integer (i.e. byte) is signed, then as per Tom and 32bitkid, signed integers are usually stored in 2's complement, where the Most Significant Bit (MSB) will determine whether a number is negative or not.

    e.g. In your example, the byte 10100100 could either represent the signed byte -92, since:

    MSB : 1 means negative
    Other 7 Bits 0100100 
    Flip and add 1 => 1011011 + 1 = 1011100
    From powers of two, right to left : 
    0*2^0 + 0*2^1 + 1*2^2 + 1*2^3 + 1*2^4 + 0*2^5 + 1*2^6
    = 4 + 8 + 16 + 64 
    = 92 (and thus -92 because of the MSB)
    

    OR if the value is an unsigned byte, then the MSB is just treated as the next power of 2, the same as all the lower bits

    i.e. 10100100 could represent:

    4 + 32 + 128 
    = 164
    

    (again, powers of two, right to left, and omitting the 0 powers of two)

    The decision as to whether an integer should is signed or not, and the number of bits required, is generally determined by the range of values that you need to store in it. For example, a 32 bit signed integer can represent the range:

    –2147483648 to 2147483647
    

    Whereas an unsigned 32 bit integer can represent numbers from

    0 to 4294967295
    

提交回复
热议问题