C# Bitwise-or operator used on a sign-extended operand; consider casting to a smaller unsigned type first
我知道这些警告可能毫无意义。。但是无论如何我都可以摆脱它们吗?
我收到了这些警告中的7条。
这与OR运算符
我强调了发出警告的原因。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | int result = (int)ror((uint)(v76 ^ (v75 | 0x862D63D3)), (uint)(BitConverter.ToInt32(v4, 72) ^ 0x22)); int v11 = (int)rol((uint)(int)((v8 & v10 | ~v10 & 0xEFCDAAC9) + v3[2] - 1126481991), 17); int v144 = (int)rol((uint)(int)((v141 & v143 | ~v143 & 0xEFCDAAC9) + v3[2] - 1126481991), 17); int v77 = (int)(`BitConverter.ToInt32(v4, 52) | 0x96C35837`); BitConverter.GetBytes((int)(v30 & 0x870DEA8A | v29)).CopyTo(v2, 32); int temp24 |= (int)(BitConverter.ToInt32(v3, 48) | 0x96B4A1B4); int v17 = (int)(BitConverter.ToInt32(v3, 12) | 0x83868A1D); |
快速的网络搜索显示了警告的正式文档,并附带说明:
The compiler implicitly widened and sign-extended a variable, and then
used the resulting value in a bitwise OR operation. This can result in
unexpected behavior.
问题是表达式
1 2 3 4 5 6 7 8 9 | class Program { public static void Main() { int v75 = int.MinValue; System.Console.WriteLine("{0:x}", v75 | 0x862D63D3); System.Console.WriteLine("{0:x}", (ulong)(long)v75 | 0x862D63D3); System.Console.WriteLine("{0:x}", (uint)v75 | 0x862D63D3); } } |
该程序打印
1 2 3 | ffffffff862d63d3 ffffffff862d63d3 862d63d3 |
如您所见,编译器默认使用第一种解释,这可能不是您想要的。
尝试将v75和其他与无符号十六进制值进行或运算的变量转换为uint:
1 | ((uint)v75 | 0x862D63D3) |
或将变量声明为
如果对int和long变量执行OR操作,则系统将int转换为long。
存在两种方式:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | namespace ConsoleApplication1 { class Program { static void Main(string[] args) { Console.WriteLine($"int.MinValue = {Convert.ToString(int.MinValue, 2)}"); Console.WriteLine($"long.MinValue = {Convert.ToString(long.MinValue, 2)}"); Console.WriteLine(); long cast1 = int.MinValue; // !!! long cast2 = unchecked((uint)int.MinValue); // !!! Console.WriteLine($"default cast = {Convert.ToString(cast1, 2)}"); Console.WriteLine($"custom cast = {Convert.ToString(cast2, 2)}"); Console.WriteLine(); Console.WriteLine($"default long OR int = {Convert.ToString(long.MinValue | int.MinValue, 2)}"); Console.WriteLine($"custom long OR int = {Convert.ToString(long.MinValue | unchecked((uint)int.MinValue), 2)}"); } } |
结果:
1 2 3 4 5 6 7 8 | int.MinValue = 10000000000000000000000000000000 long.MinValue = 1000000000000000000000000000000000000000000000000000000000000000 default cast = 1111111111111111111111111111111110000000000000000000000000000000 custom cast = 0000000000000000000000000000000010000000000000000000000000000000 default long OR int = 1111111111111111111111111111111110000000000000000000000000000000 custom long OR int = 1000000000000000000000000000000010000000000000000000000000000000 |
您想要什么结果?