Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

C语言移位运算 非法位移量的情况 #5

Open
Takanashi-Rikka1412 opened this issue Oct 4, 2021 · 0 comments
Open

C语言移位运算 非法位移量的情况 #5

Takanashi-Rikka1412 opened this issue Oct 4, 2021 · 0 comments

Comments

@Takanashi-Rikka1412
Copy link
Owner

Takanashi-Rikka1412 commented Oct 4, 2021

#include <stdint.h>
int32_t a = 123;
int32_t b1 = a >> 33;
int32_t b2 = a << 33;
int32_t b3 = a >> -31;
int32_t b4 = a >> -1;
int32_t b5 = a << -31;
int32_t b6 = a << -1;

在许多机器上(如Windows),当移动一个w位的值时,移位指令只考虑位移量的低log2w位,因此实际上位移量就是通过计算k mod w得到的。
例如上面的代码,b1实际为右移1位,b2为左移1位,b3为右移1位,b4为右移31位,b5为左移1位,b6为左移31位。

  • 不过这种转换对C程序来说没有保证,所以应该保持位移量小于待移位值的位数,且不小于0。
  • 另一方面,Java特别要求移位数量应该按照上述求模的方法来计算。
@Takanashi-Rikka1412 Takanashi-Rikka1412 changed the title C语言移位运算 C语言移位运算 非法位移量的情况 Oct 5, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant