Is there any reason to prefer signed or unsigned integers to represent lists of bits?

Viewed 113

Is there any reason to prefer signed or unsigned integers over the other to represent lists of bits?

I believe people tend to use unsigned for this more: for example, C++'s bitset converts to and from unsigned long.

Is this an arbitrary decision, or is unsigned better?

1 Answers

Using an unsigned type for integers representing bits is preferred. You'll often use the bit shift operators << and >> on these integers, and these operators have well defined behavior on unsigned integers (provided you don't shift more than the number of bits or by a negative amount).

If you use << and >> on signed integers, the former has undefined behavior if you shift bits with value 1 into or out of the sign bit, and the latter has implementation defined behavior for negative values.

Section 6.5.7 p4 and p5 of the C standard spells this out:

4 The result of E1 << E2 is E1 left-shifted E2 bit positions; vacated bits are filled with zeros. IfE1has an unsigned type, the value of the result is E1×2E2, reduced modulo one more than the maximum value representable in the result type. If E1 has a signedtype and nonnegative value, and E1×2E2 is representable in the result type, then that is the resulting value; otherwise, the behavior is undefined.

5 The result of E1 >> E2 is E1 right-shifted E2 bit positions. If E1 has an unsigned type or if E1 has a signed type and a nonnegative value, the value of the result is the integral part of the quotient of E1/2E2. If E1 has a signed type and a negative value, the resulting value is implementation-defined.

One thing you need to watch out for however is using unsigned types that are smaller than int. This is because values of those types will be promoted to int when being used in a expression.

Related