What do the C and C++ standards say about bit-level integer representation and manipulation?

(1) If all the bits in an integer type are zero, does the integer as whole represent zero?

Yes, the bit pattern consisting of all zeroes always represents 0:

The representations of integral types shall define values by use of a pure binary numeration system.49 [§3.9.1/7]

49 A positional representation for integers that uses the binary digits 0 and 1, in which the values represented by successive bits are additive, begin with 1, and are multiplied by successive integral power of 2, except perhaps for the bit with the highest position.


(2) If any bit in an integer type is one, does the integer as a whole represent non-zero? (if this is a “yes” then some representations like sign-and-magnitude would be additionally restricted)

No. In fact, signed magnitude is specifically allowed:

[ Example: this International Standard permits 2’s complement, 1’s complement and signed magnitude representations for integral types. —end
example
] [§3.9.1/7]


(3) Is there a guaranteed way to check if any bit is not set?

I believe the answer to this is “no,” if you consider signed types. It is equivalent to equality testing with a bit pattern of all ones, which is only possible if you have a way to produce a signed number with bit pattern of all ones. For an unsigned number this representation is guaranteed, but casting from unsigned to signed is undefined if the number is unrepresentable:

If the destination type is signed, the value is unchanged if it can be represented in the destination type (and bit-field width); otherwise, the value is implementation-defined. [§4.7/3]


(4) Is there a guaranteed way to check if any bit is set?

I don’t think so, because signed magnitude is allowed—0 would compare equal to −0. But it should be possible with unsigned numbers.


(5) Is there a guaranteed way to set the left-most and/or right-most bits?

Again, I believe the answer is “yes” for unsigned numbers, but “no” for signed numbers. Shifts are undefined for negative signed numbers:

Otherwise, if E1 has a signed type and non-negative value, and E1 × 2E2 is representable in the result type, then that is the resulting value; otherwise, the behavior is undefined. [§5.8/2]

Leave a Comment