逻辑、算术按位移位

发布于 2024-09-19 16:52:26 字数 440 浏览 2 评论 0原文

试图澄清一些事情。

据我了解,对于算术、逻辑按位移位:

  1. << 对于两个
  2. >> 移位的工作原理相同,不同之处在于逻辑移位始终会填充字节用 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:

  1. << work the same for both
  2. >> 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

贪了杯 2024-09-26 16:52:26

对于非负数,两种右移是相同的。仅当要移位的数字为负数时才会出现差异。

实际上C标准并没有规定当数字为负数时>>何时进行逻辑或算术移位,但通常情况下,它会进行算术移位。要执行逻辑移位,必须将数字转换为相应的无符号类型,例如

int x = -2;
int y = x >> 1;    // arithmetic shift.
assert (y == -1);
int z = (unsigned)x >> 1;  // logical shift.
assert (z == 0x7FFFFFFF);

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:

int x = -2;
int y = x >> 1;    // arithmetic shift.
assert (y == -1);
int z = (unsigned)x >> 1;  // logical shift.
assert (z == 0x7FFFFFFF);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文