July 29, 2008 at 5:03 pm
We have a bigint number (64 bits), and I need to retrive a bit value ( 1 or 0) for a given bit number. What is the most efficient way to do it ?
Thanks
August 8, 2008 at 3:46 am
If your bit numbering starts from right to left, this could be what you need:
declare @Value bigint, -- The value we want to analyse
@BitToTest tinyint -- The number of the bit we want to test (starting with 0)
set @Value = 123456789 -- Binary: 111010110111100110100010101 (left out leading 0s)
-- We have to:
-- * Create a mask (bigint), i.e. 1 shifted to left @BitToTest times
-- A left shift is easyly implemented using powers of 2
-- * AND the mask with the @Value
-- * Convert the result to bit
-- For example we want to test bit 7 (the 8th bit from the right side), which should be 0
set @BitToTest = 7
select CAST(@Value & POWER(2, @BitToTest) as bit) 'BitSet?'
/* Result
BitSet?
-------
0
(1 Row(s) affected)
*/
-- Other example: Test bit 4 (the 5th bit from the right side), which should be 1
set @BitToTest = 4
select CAST(@Value & POWER(2, @BitToTest) as bit) 'BitSet?'
/* Result:
BitSet?
-------
1
(1 Row(s) affected)
*/
Viewing 2 posts - 1 through 1 (of 1 total)
You must be logged in to reply to this topic. Login to reply