c – 位操作的标准(跨平台)方式

前端之家收集整理的这篇文章主要介绍了c – 位操作的标准(跨平台)方式前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
由于数字是不同的二进制表示(例如,采取大/小的endian),这是跨平台:
// NOTE: FIXED-SIZE unsigned integral type
some_unsigned_type variable = some_number;

// set n-th bit,starting from 1,// right-to-left (least significant-to most significant)
variable |= ( 1 << ( n - 1 ) );

// clear the same bit:    
variable &= ~( 1 << ( n - 1 ) );

换句话说,编译器是否总是处理固定大小的无符号数字的不同二进制表示,或者它是平台特定的?

如果变量是有符号的积分类型(例如,int),它的值是

>零
>积极
>否定

标准说了什么?

附:而且,是的,我在C和C都很有趣,请不要告诉我他们是不同的语言,因为我知道这个:)

我可以粘贴真实的例子,如果需要,但是这个帖子会变得太长

解决方法

免责声明:我隐含地假设你正在谈论一个固定宽度的整数类型.位移否则是相当危险的…

标准:n3337 C 11

移位的定义是带符号类型(*)中的无符号类型或正值的数学,因此不受底层硬件表示的影响.

5.8 Shift operators [expr.shift]

2 The value of E1 << E2 is E1 left-shifted E2 bit positions; vacated bits are zero-filled. If E1 has an unsigned type,the value of the result is E1 × 2E2,reduced modulo one more than the maximum value representable in the result type. 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.

3 The value 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 non-negative 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.

同样的原因,我会认为按位,或否定是可以的:它们是在数学上定义的.

5.3.1 Unary operators [expr.unary.op]

10 The operand of ˜ shall have integral or unscoped enumeration type; the result is the one’s complement of its operand.

5.11 Bitwise AND operator [expr.bit.and]

1 The usual arithmetic conversions are performed; the result is the bitwise AND function of the operands. The operator applies only to integral or unscoped enumeration operands.

5.13 Bitwise inclusive OR operator [expr.or]

1 The usual arithmetic conversions are performed; the result is the bitwise inclusive OR function of its operands. The operator applies only to integral or unscoped enumeration operands.

不过,我承认,对于后两者来说,我不那么肯定,我找不到按位XX功能的任何定义,所以即使我相信他们是数学对应的,我也不能保证.

(*)感谢phresnel指出.

猜你在找的C&C++相关文章