按位运算
有时,对实际上是位掩码的整数字段执行操作会很有用,该位掩码包含由二进制位表示的一组布尔值。例如,一个 8 字节的整数值可能包含 64 位的信息,这些信息涉及一组开关,其状态要么为 1(开),要么为 0(关)。要确定开关的状态或设置其值,通常会使用 SQL 按位运算符 AND、OR 和 NOT。另一个常见的按位运算符 XOR 不是标准 SQL,但作为内置函数 xor() 提供。
例如,以下操作将数据库字段中的位与整数值 3(二进制 00000000000000000000000000000011)进行比较,该字段初始化为值 255(二进制 00000000000000000000000011111111):
XSQL>create table x(a integer);
XSQL>insert into x values (255);
XSQL>select a and 3 from x;
#1
------------------------------------------------------------------------------
3
Selected records: 1
XSQL>select a or 3 from x;
#1
------------------------------------------------------------------------------
255
Selected records: 1
XSQL>select not a from x;
#1
------------------------------------------------------------------------------
-256
Selected records: 1
XSQL>select xor(a,3) from x;
#1
------------------------------------------------------------------------------
252
Selected records: 1
请注意使用函数 xor() 来获取“a 异或 3”的值。还要注意,NOT 运算符的结果实际上等同于 C 语言中的 ~ 运算符,由于 SmartESQL 在内部将中间值存储为 8 字节整数值,所以结果可能为负数。正如链接:http://www.geeksforgeeks.org/interesting-facts-bitwise-operators-c/ 中所解释的那样,在使用按位取反时应格外小心,以下是一个用 C 语言编写的示例程序:
// Note that the output of following program is compiler dependent
int main()
{
unsigned int x = 1;
printf("Signed Result %d \n", ~x);
printf("Unsigned Result %ud \n", ~x);
return 0;
}
Output:
Signed Result -2
Unsigned Result 4294967294d