terça-feira, 28 de dezembro de 2010

Bitwise operations

Most SQL implementations (like MySQL, PostgreSQL, MS SQL, SQLite, etc) provide bitwise operators (like ~, &, |, etc). The Oracle database doesn't support bitwise operators, but supports a bitAND function that can be used to provide similar functionality.

Oracle's bitAND (most SQL implementations use the & operator):

SQL> SELECT bitand(2, 4) FROM dual;
BITAND(2,4)
-----------
          0

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

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

To simulate bitNOT (most SQL implementations use the ~ operator):

CREATE FUNCTION bitnot(x IN NUMBER) RETURN NUMBER AS 
BEGIN
    RETURN (0 - x) - 1;
END;
/

Nenhum comentário :

Postar um comentário

Related Posts Plugin for WordPress, Blogger...