Tuesday, May 29, 2007

Oracle Bitwise Operations

Oracle has a function (although it took me a while to find) in it's documentation to perform a BITAND function. This will take two numbers, convert them both to binary values, and then compares the two numbers at the bit level. If both numbers have a bit turned on in the same place then it evaluates to 1, otherwise is returns a 0. However there doesn't appear to be a built in BITOR and BITXOR function in Oracle. After a few Google searches I found this page that has two functions that seem to work correctly to provide you the BITOR and BITXOR functionality. BITOR:
CREATE OR replace FUNCTION bitor( x IN NUMBER, y IN NUMBER ) RETURN NUMBER  AS
BEGIN
   RETURN x + y - bitand(x,y);
END;
/
BITXOR:
CREATE OR replace FUNCTION bitxor( x IN NUMBER, y IN NUMBER ) RETURN NUMBER  AS
BEGIN
   RETURN bitor(x,y) - bitand(x,y);
END;
/