逻辑、算术按位移位
试图澄清一些事情。
据我了解,对于算术、逻辑按位移位:
<<
对于两个>>
移位的工作原理相同,不同之处在于逻辑移位始终会填充字节用 0 填充,而算术移位将用符号位填充它。
我如何使用 C 来区分这个?
据我了解,实际的运算符是相同的 <<
,>>
命令之间有何不同:
int i=1;
printf ("%d\n", i >> 1); // logical shift
int j=1;
printf ("%d\n", j >> 1); // arithmetical shift
请告诉我,
Seeking to clarify something.
It is my understanding that with regard to arithmetical, logical bitwise shifts:
<<
work the same for both>>
shifts differ in that logical shift will always pad byte with 0, whereas arithmetical shift will pad it with the sign bit.
How can I differentiate this using C?
From what I understand, actual operators are the same <<
,>>
How would command differ between:
int i=1;
printf ("%d\n", i >> 1); // logical shift
int j=1;
printf ("%d\n", j >> 1); // arithmetical shift
Please let me know,
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
对于非负数,两种右移是相同的。仅当要移位的数字为负数时才会出现差异。
实际上C标准并没有规定当数字为负数时
>>
何时进行逻辑或算术移位,但通常情况下,它会进行算术移位。要执行逻辑移位,必须将数字转换为相应的无符号类型,例如:In case of nonnegative numbers, both kinds of right-shifts are the same. The difference appears only when the number to shift is negative.
Actually the C standard does not specify when should
>>
perform logical or arithmetic shift when the number is negative, but typically, it performs arithmetic shift. To perform logical shift, the number must be cast to the corresponding unsigned type, for example: