count expressions, the actual shift count depends o-6ren">
gpt4 book ai didi

c# - 为什么下面的位移位操作没有丢弃向左移动的位?

转载 作者:太空宇宙 更新时间:2023-11-03 20:48:57 26 4
gpt4 key购买 nike

假设我写了以下内容:

Console.WriteLine("{0:X8}", (uint)1 << 31);

它返回 80000000(如预期)。

但是,如果我写:

Console.WriteLine("{0:X8}", (uint)1 << 32);

它返回 00000001

我希望“1”位被丢弃,结果为 00000000

这是documentation说:

The left-shift operation discards the high-order bits that are outside the range of the result type and sets the low-order empty bit positions to zero.

确实,如果我这样写:

Console.WriteLine("{0:X8}", (uint)0xFA << 28);

它返回 A0000000(F 被丢弃)

最佳答案

来自同一个documentation page :

For the x << count and x >> count expressions, the actual shift count depends on the type of x as follows:

  • If the type of x is int or uint, the shift count is defined by the low-order five bits of the right-hand operand. That is, the shift count is computed from count & 0x1F (or count & 0b_1_1111).

32 & 0x1F0 .

这个“陷阱”已经够糟了,前 C# 设计团队成员 Eric Lippert 将其命名为 the 8th worst C# feature .

关于c# - 为什么下面的位移位操作没有丢弃向左移动的位?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57481056/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com