简体   繁体   English

移位右操作数类型

[英]bit-shift right-hand operand type

I'm wondering what the correct right-hand operand is for C/C++ bit-shift operators.我想知道 C/C++ 移位运算符的正确右手操作数是什么。

At time of writing, the built-in arithmetic types are all less than 256 bits, so a single byte would be sufficient.在撰写本文时,内置算术类型都小于 256 位,因此单个字节就足够了。 Furthermore, x86 shift-instructions use imm8 .此外, x86 移位指令使用imm8 Together this suggests the right-hand operand should be an unsigned char and use of a different type here will require type-conversion.这表明右手操作数应该是一个unsigned char ,并且在这里使用不同的类型将需要类型转换。

Is there a "most correct" type to use here?这里有“最正确”的类型吗? I know the standard is strangely lenient about other aspects of bit-shifting so maybe this is another case of the same?我知道标准对位移的其他方面非常宽松,所以也许这是另一种相同的情况?

Any integer type can be used as the right operand of a bitwise shift, so long as the value is at least 0 and less than the bit length of the left operand.任何 integer 类型都可以用作按位移位的右操作数,只要该值至少为 0 且小于左操作数的位长。

This is spelled out in section 6.5.7p2 of the C standard regarding Bitwise Shift Operators:这在C 标准的第 6.5.7p2 节中关于按位移位运算符进行了详细说明:

The integer promotions are performed on each of the operands. integer 提升在每个操作数上执行。 The type of the result is that of the promoted left operand.结果的类型是提升的左操作数的类型。 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.如果右操作数的值为负数或大于或等于提升的左操作数的宽度,则行为未定义。

C tends to want to do everything as at least int , so it would be very surprising if the RHS of << and >> were to be specified as unsigned short or unsigned char . C 倾向于至少以int的形式执行所有操作,因此如果将<<>>的 RHS 指定为unsigned shortunsigned char将非常令人惊讶。

It's hard to imagine why a programmer would ever use long (or, god help us, long long ) there, but I just tried this code:很难想象为什么程序员会在那里使用long (或者,上帝帮助我们, long long ),但我只是尝试了这段代码:

int main()
{
    int x = 16;
    long int y = 2;
    int z1 = x << y;
    int z2 = x >> y;
    printf("%d %d\n", z1, z2);

    long long int y2 = 2;
    z1 = x << y2;
    z2 = x >> y2;
    printf("%d %d\n", z1, z2);
}

I compiled it under two compilers, and neither gave any warnings, and both programs printed 64 4 .我在两个编译器下编译它,都没有给出任何警告,两个程序都打印了64 4 (Not a conclusive test, but suggestive.) (不是结论性的测试,但具有启发性。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM