Assume the below scenario:
A system checks a stock level for a grocery store that sells 3 items and whenever a certain item runs out it flags up a message.
Say the 3 items are:
To make use of binary masking (also known as bitwise) to be able to track which needs to be highlighted, we need to do the following:
1) We will assign a binary number to each one of the item, 1 for denoting we need to flag a message and 0 f0r doing nothing. Each of the the items in turn will have a fixed position. So in this instance there are three position for three items and we can assign it as below:
Item Position Binary Value
—– ——— ————-
Mango 0 1
Orange 1 0
Apple 2 1
2) Now, we need a single decimal number that represents which items jave a binary 1 to flag a message and which don’t. To do that we use the Position value and treat that as the power of 2.
So, we use Position 1 and 3 (because those have the binary value 1 binded) and it should equate to:
(2^0) = 1
+ (2^2) = 4
Total = 5
3) The value 5 can then be sent to the section of the system which flags messages. It should then have a script to reverse it back to a binary number which is 101.
The position number is fixed and therefore can be easily be deduced as to which binary number is binded to whcih item.
This way by only sending an integer number we can for a group of item attached and interchagne flag data.
>Returns the binary representation of a number:
-- courtesy to a script somewhere in the internet
CREATE FUNCTION [csrt].[udf_ReturnBinaryPattern]
DECLARE @Pattern CHAR(8)
SET @Pattern = ''
SELECT @Pattern = convert(VARCHAR,+(@Byte & 1) / 1) +
convert(VARCHAR,(@Byte & 2) / 2) +
convert(VARCHAR,(@Byte & 4) / 4) +
convert(VARCHAR,(@Byte & 8) / 8) +
convert(VARCHAR,(@Byte & 16) / 16) +
convert(VARCHAR,(@Byte & 32) / 32) +
convert(VARCHAR,(@Byte & 64) / 64) +
convert(VARCHAR,(@Byte & 128) / 128)
>Optional – Explaning & bitwise AND operator:
The binary representation of 170 (a_int_value or A) is 0000 0000 1010 1010. The binary representation of 75 (b_int_value or B) is 0000 0000 0100 1011. Performing the bitwise AND operation on these two values produces the binary result 0000 0000 0000 1010, which is decimal 10.
SELECT 170 & 75
Result is 10 (thisis a decimal number)
The & operator tranforms number or charters into binary and then adds them up:
170 = 0000 0000 1010 1010
75= 0000 0000 0100 1011
10 = 0000 0000 0000 1010
Another artice: http://sqlfool.com/2009/02/bitwise-operations/
Read Full Post »