Thursday, October 13, 2011

Bitwise Operations in SQL

I have been working on a ticket that requires a privilege to be enabled on a POS device for all the retailers. doing my research, I found that there were about 14 privileges for a POS device that you can enable/disable by checking/unchecking the flag from the POS maintenance UI we have. I have to do this for 16,000 POS devices and using the UI to do this is not a feasible approach. I have to do a mass update in the Database.
Further looking at it, I found that the privileges are clubbed together and calculated and stored in the Database as a long decimal bitmap value. each of the 14 privileges are represented as static final long variable of 16 bit hexadecimal values like,
 long POS_PRIVILEGE_BIT_BALANCE_INQUIRY = 0x1000000000000000L.
these are used while calculating the long decimal bitmap.
Now to enable the Balance inquiry bit, all I have to do is convert the about hexadecimal value to decimal and do a bitwise OR with the existing decimal bitmap from teh database. this way if the balance inquiry bit is enabled the result of bitwise OR will be same, and if it is disabled, the result will be a decimal number with this bit enabled. so I wont be breaking anythign if the balance inquiry is already enabled for any POS devices.
SQL provides a function called bitAND(x,y). with bitAND you can calculate bitOR as x + y - bitAND(x,y). you can calculate bitwise XOR, NAND, NOR etc as well.

my query for bitwise OR would be something like this,
select (-3511118859488722944 + 1152921504606846976) - bitAND(-3511118859488722944, 1152921504606846976) as bitOR from dual;

-3511118859488722944 is the existing privileges in decimal in the database.
1152921504606846976 is the balance inquiry bit in decimal.

how do I test whether what I am doing is correct ? I will test for 2 things.
1. I do a bitwise AND (&) with the decimal bitmap and the decimal balance inquiry value, If I get the result as 0 that means the balance inquiry bit is disabled. If the result is non zero than the bit is selected.
2. I take the decimal bitmap from database and update the balance inquiry bit in it by doing a bitwise OR with the balance inquiry static value. i get a new decimal number. now if I do a bitwise XOR with the previous value and new value I must get the balance inquiry decimal value. because thats the only bit I changed. awesome application of XOR here!

My colleague Bobe helped me in understanding the application of these bitwise operations. Also I learned using windows calculator for all these number conversion and bitwise operations.

here is an article to understand what bitwise OR is http://en.wikipedia.org/wiki/Exclusive_or. most of us know this and much more from our books but applying them is more pleasing!

No comments:

Post a Comment