C# bit shift : is this behavior in the spec, 是一个错误,还是偶然的?

标签 c# bit-shift

我正在使用位移运算符(参见我的问题 Bit Array Equality),一位 SO 用户指出了我计算移位操作数时的错误——我计算的范围是 [1,32] 而不是 [0 ,31] 对于一个整数。 (为 SO 社区欢呼!)

在修复问题时,我惊讶地发现了以下行为:

-1 << 32 == -1

事实上,这似乎是 n << s被编译(或由 CLR 解释——我没有检查 IL)为 n << s % bs(n)其中 bs(n) = n 的大小,以位为单位。

我本以为:

-1 << 32 == 0

编译器似乎意识到您的移动超出了目标的大小并纠正了您的错误。

这纯粹是一个学术问题,但有谁知道这是否在规范中定义(我在 7.8 Shift operators 找不到任何内容),只是一个未定义行为的偶然事实,或者是否存在这可能产生的情况错误?

最佳答案

我相信规范的相关部分在这里:

For the predefined operators, the number of bits to shift is computed as follows:

  • When the type of x is int or uint, the shift count is given by the low-order five bits of count. In other words, the shift count is computed from count & 0x1F.

  • When the type of x is long or ulong, the shift count is given by the low-order six bits of count. In other words, the shift count is computed from count & 0x3F.

如果生成的移位计数为零,则移位运算符简单地返回值 的 x。

320x20 .表达式 0x20 & 0x1F评估为 0 .因此,移位计数为零,不进行移位;表达式 -1 << 32 (或任何 x << 32 )只返回原始值。

关于C# bit shift : is this behavior in the spec, 是一个错误,还是偶然的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2326724/

相关文章:

c# - ToList() 删除是否需要解决 "Access to Modified Closure"resharper 警告?

c# - 适用于 .Net 应用程序的基于 OMR 的软件

c - C语言中<<是什么意思?

javascript - 什么是 JavaScript >>> 运算符以及如何使用它?

c# - EF Core 3.1 ExecuteSqlRaw/ExecuteSqlRawAsync 是否是 ExecuteSqlCommand/ExecuteSqlCommandAsync 的直接替代品?

c# - 使用 LINQ to SQL;如何在不设置所有列值的情况下在表中插入行?

c# - 如何在控制台应用程序中将列表打印为表格?

c# - 左移 255(作为一个字节)

java - 如何将多个小整数保存在一个整数中以进行位移位?

c++ - 使用位移位定义的宏值