C# 来自按位 (&) 表达式的意外结果
C# Unexpected results from bitwise (&) expression
我得到了意想不到的结果(可能是因为我误用或误解了按位 (&) 表达式的工作原理)。我有以下代码:
string sbin = "10010110"; // 150 = 1001 0110
uint ival = Convert.ToUInt32(sbin, 2);
ival.Dump(); // 150 Expected Correct
uint lval = ival << 16; // Shift 16 bits left
lval.Dump(); // 9830400 - Expected Correct
string slval = Convert.ToString(lval, 2);
slval.Dump(); // 0000 0000 1001 0110 0000 0000 0000 0000 - Expected Correct
uint lrval = lval & ival; // <--- This is where I am confused (while a '+' operator works, why does the & not return the proper result?)
// expecting 0000 0000 1001 0110 0000 0000 1001 0110 (aka 9830550 (dec))
lrval.Dump(); // returns 0,
我正在寻找有关我的逻辑失败之处的解释。我希望完成的最终表达是:
uint xpos = 150;
uint ypos = 150;
uint val = ((xpos) & ((ypos) << 16))); // result is 0, should be 9830550 as above)
当然
((xpos) + ((ypos) << 16))); // Would work properly
但是我看到的所有示例(出于鼠标位置 (POINT) 位置的目的都在表达式中显示了“&”)
这是你的两个数字的二进制表示:
00000000 00000000 00000000 10010110
00000000 10010110 00000000 00000000
所以应该很清楚,两个数字中不会有 1
位,所以当你对这些数字进行按位运算时,结果是 0
.
我得到了意想不到的结果(可能是因为我误用或误解了按位 (&) 表达式的工作原理)。我有以下代码:
string sbin = "10010110"; // 150 = 1001 0110
uint ival = Convert.ToUInt32(sbin, 2);
ival.Dump(); // 150 Expected Correct
uint lval = ival << 16; // Shift 16 bits left
lval.Dump(); // 9830400 - Expected Correct
string slval = Convert.ToString(lval, 2);
slval.Dump(); // 0000 0000 1001 0110 0000 0000 0000 0000 - Expected Correct
uint lrval = lval & ival; // <--- This is where I am confused (while a '+' operator works, why does the & not return the proper result?)
// expecting 0000 0000 1001 0110 0000 0000 1001 0110 (aka 9830550 (dec))
lrval.Dump(); // returns 0,
我正在寻找有关我的逻辑失败之处的解释。我希望完成的最终表达是:
uint xpos = 150;
uint ypos = 150;
uint val = ((xpos) & ((ypos) << 16))); // result is 0, should be 9830550 as above)
当然
((xpos) + ((ypos) << 16))); // Would work properly
但是我看到的所有示例(出于鼠标位置 (POINT) 位置的目的都在表达式中显示了“&”)
这是你的两个数字的二进制表示:
00000000 00000000 00000000 10010110 00000000 10010110 00000000 00000000
所以应该很清楚,两个数字中不会有 1
位,所以当你对这些数字进行按位运算时,结果是 0
.