// NOTE: FIXED-SIZE unsigned integral typesome_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
isE1
left-shiftedE2
bit positions; vacated bits are zero-filled. IfE1
has an unsigned type,the value of the result isE1 × 2
E2
,reduced modulo one more than the maximum value representable in the result type. Otherwise,ifE1
has a signed type and non-negative value,andE1×2
E2
is representable in the result type,then that is the resulting value; otherwise,the behavior is undefined.3 The value of
E1 >> E2
isE1
right-shiftedE2
bit positions. IfE1
has an unsigned type or ifE1
has a signed type and a non-negative value,the value of the result is the integral part of the quotIEnt ofE1/2
E2
. IfE1
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 – 位 *** 作的标准(跨平台)方式所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)