在C中以常数进行的位偏移与通过具有相同值的变量的位偏移之间是否有区别? [英] Is there a difference between bitshift by a constant versus bitshifting by a variable with the same value, in C?

查看:85
本文介绍了在C中以常数进行的位偏移与通过具有相同值的变量的位偏移之间是否有区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将值0xFFFFFFFF移位32位,并且正确地 如果我写,则为0

I'm attempting to bitshift the value 0xFFFFFFFF by 32 bits, and it correctly comes to 0 if I write

x = x << 32;

无论如何保持为0xFFFFFFFF

我写的时候:

x = x << y

y = 32

我真的一点都不明白.

不过,对于要按32 - n

修改

如果未定义<< 32,那么我真的无法感知到一种创建将n-高位填充1的函数的方法

If << 32 is undefined, then I really can't perceive a way to create a function that pads n - upper bits with 1's

推荐答案

它是未定义的行为移位一个或多个变量的位长.在C99标准草案的6.5.7 按位移位运算符

It is undefined behavior to shift by the bit length of a variable or greater. From the draft C99 standard section 6.5.7 Bitwise shift operators:

[...]如果右操作数的值为负或大于或等于提升后的左操作数的宽度,则行为是不确定的.

[...]If the value of the right operand is negative or is greater than or equal to the width of the promoted left operand, the behavior is undefined.

正如Pascal所说,您需要制作一个特例或使用更宽的字体.

As Pascal says, you need to make a special case or use a wider type.

gcc在某些情况下可能会为此实时查看生成警告:

gcc in some cases can generate a warning for this see it live:

警告:左移计数> =类型的宽度[默认启用]

warning: left shift count >= width of type [enabled by default]

这篇关于在C中以常数进行的位偏移与通过具有相同值的变量的位偏移之间是否有区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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