Search code examples
cintunsigned-integer

What's the difference between int and unsigned-int value representations in bits in C


I noticed by experiment that in unsigned int the value of a number is represented in 32 bit even if the number is taking 1-bit space, the rest of the bits would take 0 as a value. While in int, the value is being put in the bits needed with just 1 more bit added for the sign. Can someone please explain to me what's that?


Solution

  • i noticed by experiment that in unsigned int the value of a number is represented in 32 bit even if the number is taking 1-bit space, the rest of the bits would take 0 as a value. while in int, the value is being put in the bits needed with just 1 more bit added for the sign. can someone please explain to me what's that?

    Sure. You're mistaken.

    The C standard specifies that, as corresponding unsigned and signed integer types, unsigned int and (signed) int require the same amount of storage (C2011 6.2.5/6). The standard does not specify the exact sizes of these types, but 32 bits is a common choice. If the representation of an unsigned int takes 32 bits in a given C implementation, then so does the representation of that implementation's int.

    Furthermore, although C allows a choice from among 3 alternative styles of negative-value representation, the correspondance between signed and unsigned integer representations is defined so that the value bits in the representation of an int -- those that are neither padding bits nor the one sign bit -- represent the same place value as the bits in the same position of the corresponding unsigned integer type (C2011, 6.2.6.2/2). Thus, the representation of a signed integer with non-negative value can be reinterpreted as the corresponding unsigned integer type without changing its numeric value.