将整数左移32位 [英] Left shift an integer by 32 bits

查看:203
本文介绍了将整数左移32位的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在GCC下,如果 num1s == 0 ,则以下代码始终返回<< 的左操作数:

Under GCC, the following code always return the left operand of << if num1s == 0:

0xFFFFFFFFu << (32-num1s);

阅读为什么不对32位整数进行左移移位 使用32次以上是否可以正常工作?,并且按David Heffernan引用的标准,似乎如果左操作数为 unsigned ,则它是已定义的操作。只有当E1(左操作数)具有带符号的类型和非负值时,它才可能导致未定义的行为。

After reading Why doesn't left bit-shift, "<<", for 32-bit integers work as expected when used more than 32 times?, and the standard quoted by David Heffernan, it seems that if the left operand is unsigned, it is a defined operation. It is only when E1 (the left operand) has a signed type and non-negative value that it could result in undefined behavior.

任何人都可以解释标准是否声明了吗?明确指出,如果移位的数量大于类型包含的位数,则为未定义的行为

Can any one explain if the standard states explicitly that if the amount shifted is larger than the number of bits the type contains, it is undefined behavior?

推荐答案

§5.8移位运算符


结果的类型是提升后的左操作数的类型。 如果右操作数为负或大于或等于提升后的左操作数的位长度,则该行为是不确定的。

E1<< E2 E1 左移 E2 位的位置;空出的位为零。如果 E1 具有无符号类型,则结果的值为 E1×2E2 ,其模值比最大值减少了1结果类型中可表示的值。否则,如果 E1 具有带符号的类型且非负值,并且 E1×2E2 可表示为结果类型,那就是结果值;否则,行为是不确定的。

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.

这篇关于将整数左移32位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆