有什么理由更喜欢用有符号或无符号整数来表示位列表吗?
Is there any reason to prefer signed or unsigned integers to represent lists of bits?
是否有任何理由优先使用有符号或无符号整数来表示位列表?
我相信人们更倾向于使用 unsigned
:例如,C++ 的 bitset
与 unsigned long
之间的转换。
这是一个武断的决定,还是 unsigned
更好?
最好对表示位的整数使用无符号类型。您将经常对这些整数使用移位运算符 <<
和 >>
,并且这些运算符对无符号整数具有明确定义的行为(前提是您的移位不超过位数或负数)。
如果对有符号整数使用 <<
和 >>
,如果将值为 1 的位移入或移出符号位,前者有 undefined behavior,而后者有负值的实现定义行为。
C standard 的第 6.5.7 节 p4 和 p5 详细说明了这一点:
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.
然而,您需要注意的一件事是使用小于 int
的无符号类型。这是因为这些类型的值在表达式中使用时将被提升为 int
。
是否有任何理由优先使用有符号或无符号整数来表示位列表?
我相信人们更倾向于使用 unsigned
:例如,C++ 的 bitset
与 unsigned long
之间的转换。
这是一个武断的决定,还是 unsigned
更好?
最好对表示位的整数使用无符号类型。您将经常对这些整数使用移位运算符 <<
和 >>
,并且这些运算符对无符号整数具有明确定义的行为(前提是您的移位不超过位数或负数)。
如果对有符号整数使用 <<
和 >>
,如果将值为 1 的位移入或移出符号位,前者有 undefined behavior,而后者有负值的实现定义行为。
C standard 的第 6.5.7 节 p4 和 p5 详细说明了这一点:
4 The result of
E1 << E2
isE1
left-shiftedE2
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. IfE1
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
isE1
right-shiftedE2
bit positions. IfE1
has an unsigned type or ifE1
has a signed type and a nonnegative value, the value of the result is the integral part of the quotient of E1/2E2. IfE1
has a signed type and a negative value, the resulting value is implementation-defined.
然而,您需要注意的一件事是使用小于 int
的无符号类型。这是因为这些类型的值在表达式中使用时将被提升为 int
。