& – Bitwise AND 按位与,都为真才为真 | – Bitwise OR 按位或,只要有一个为真就为真 ~ – One’s complement 取反 ^ – Bitwise XOR 按位异或,只有一个为假时为真 << – left shift 左移 大多数情况下可以理解为左移a位就是乘以2^a >> – right shift 左移 大多数情况下可以理解为右移a位就是除以2^a
这6种运算符中,除了取反~运算符外,其它的都是二目运算符,就是要求运算符两侧各有一个运算量,运算量是整型或者字符型的数据
位运算能干的还挺多,比如swap功能(数值交换),奇偶性判断,左移右移在计算oracle rdba时更方便
#include <stdio.h> void main() { int a=12,b=14; a^=b; b^=a; a^=b; printf("A=%d,B=%d\n",a,b); printf("Average is %d\n",(a+b)>>1); if((a&1)==1) { printf("A is odd\n"); } else { printf("A is even\n"); } printf("The int range is %d\n",(1<<31)-1); int rdba=0xff4062ff; int file=0x3FF&(rdba>>22); int block=rdba&0x3FFFFF; printf("File=%d,Block=%d\n",file,block); }
Oracle的bitand函数
SQL> select bitand(6,3) from dual; BITAND(6,3) ----------- 2 SQL> select bitand( bin_to_num(1,1,0), bin_to_num(0,1,1)) value from dual; 2 3 4 VALUE ---------- 2 SQL>
以下引自orafaq
oracle's bitand (most sql implementations use the & operator):
sql> select bitand(2, 4) from dual;
bitand(2,4)
-----------
0
A.to simulate bitor (most sql implementations use the | operator):
create function bitor(x in number, y in number) return number as begin return x + y - bitand(x,y); end; / sql> select bitor(2, 4) from dual; bitor(2,4) ---------- 6
B.to simulate bitxor (most sql implementations use the ^ operator):
create function bitxor(x in number, y in number) return number as begin return bitor(x,y) - bitand(x,y); end; / sql> select bitxor(2, 4) from dual; bitxor(2,4) ----------- 6
C.to simulate bitnot (most sql implementations use the ~ operator):
create function bitnot(x in number) return number as begin return (0 - x) - 1; end; /
其实utl_raw也包含类似的函数
SQL> desc utl_raw
FUNCTION BIT_AND RETURNS RAW Argument Name Type In/Out Default? ------------------------------ ----------------------- ------ -------- R1 RAW IN R2 RAW IN FUNCTION BIT_COMPLEMENT RETURNS RAW Argument Name Type In/Out Default? ------------------------------ ----------------------- ------ -------- R RAW IN FUNCTION BIT_OR RETURNS RAW Argument Name Type In/Out Default? ------------------------------ ----------------------- ------ -------- R1 RAW IN R2 RAW IN FUNCTION BIT_XOR RETURNS RAW Argument Name Type In/Out Default? ------------------------------ ----------------------- ------ -------- R1 RAW IN R2 RAW IN
Reference
http://www.orafaq.com/wiki/Bit
http://www.thegeekstuff.com/2012/10/bitwise-operators/