where子句中的按位运算符 [英] Bitwise Operators in a where clause
问题描述
我对按位运算符是完全陌生的,并且我无法确定数据库中的值是否可以正确计算出.
I am completely new to bitwise operators and I having trouble figuring out values in a database are calculating out correctly.
INSERT INTO @ObjectCounts (CountOf, Server, Total)
(SELECT 'RandomString', CAST(ServerGUID AS varchar(40)), COUNT(*) AS Num
FROM TableName
WHERE (Flags & (8 | 16) = 16)
在Flags列中将值写为"2359624","35160","2360072"给出了一些示例,而where子句让我感到困惑.
我在Google上找到的示例将两个值的数字转换为二进制,然后将它们加在一起?无论如何,由于不了解按位运算的工作原理,我不知道该运算符的值将变成16.
The where clause is what is getting me as the values in the Flags column are written out as "2359624", "35160", "2360072" to give a few examples.
The examples I found on google are translating the numbers of two values into binary and then adding them together? In any case, I don''t know how the value of this operator would turn into 16 because I don''t understand how the bitwise operation works.
推荐答案
在查看按位运算符时,首先要做的是停止查看十进制数字!而是将它们翻译为十六进制:
When looking at bit wise operators, the first thing to do is stop looking at numbers in decimal! Translate them to Hex instead:
Dec Hex
2359624 -> 0x240148
35160 -> 0x008958
2360072 -> 0x240308
8 -> 0x000008
16 -> 0x000010
现在就说得通了!
Now it makes sense!
WHERE Flags & (8 | 16) = 16)
翻译为:
WHERE bit 3 of Flags is zero AND bit 4 of Flags is one
,原因是:
Because:
8 | 16 -> 0x08 | 0x10 -> 0x18
然后
Flags & (8 | 16) -> Flags & 0x18
仅返回标志的原始Bit 3和Bit 4值-所有其他位都被AND运算符丢弃.
最后,将该值与16(或0x10)进行比较,因此它希望第4位打开,第3位关闭.
您提供给我们的所有Flags
示例都没有通过该测试!
Which returns only the original Bit 3 and Bit 4 values of Flags - all other bits are discarded by the AND operator.
Finally, that value is compared against 16 (or 0x10) so it wants bit 4 on, and bit 3 off.
And none of the Flags
examples you gave us passes that test!
如果我理解您想找出flags列包含8还是16(使用位计算).如果正确,请分别进行比较.例如:
If I understood you want to find out if the flags column contains 8 or 16 (using bit calculations). If that''s correct, compare them separately. For example:
... WHERE FLAGS & 8 = 8 OR FLAGS & 16 = 16
例如,请考虑以下内容:
For example consider following:
select 31 & 16
结果是16和
Result is 16 and
select 31 & 8
结果是8
和
Result is 8
and
select 32 & 8
结果为0
result is 0
这篇关于where子句中的按位运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!