SQL Server Central is supported by Red Gate Software Ltd.
 
Log in  ::  Register  ::  Not logged in
Search:  
 
 

Convert Interger to Binary String for Bit Masks

By rrinchuse, 2003/03/21

Total article views: 69 | Views in the last 30 days: 2

The three functions here can be used to store Bit Masks as Integers.

These are functions to convert an integer into a binary string.
This can be useful if you store Bit Masks in your database as integers.

For example .. '00000000000011111001001001110011' to 1020531
Each Bit could represent an ON or OFF value. One integer column
could be equivalent to having 32 individual bit columns in your table.

There are three functions:

fn_GetBitString .. converts an integer to a bit string of a given size up to 32bit
fn_GetIntFromBitString .. converts a bit string to an integer
fn_GetBit .. get a specific bit value by bit location of an integer

Here are some example calls ..

DECLARE @I1 int, @I2 int

SELECT @I1 = dbo.fn_GetIntFromBitString('0101')
SELECT @I2 = dbo.fn_GetIntFromBitString('1001')

--Show Each Bit one at a time of the first integer
PRINT Cast(dbo.fn_GetBit(@I1,4) as char(1))
+Cast(dbo.fn_GetBit(@I1,3) as char(1))
+Cast(dbo.fn_GetBit(@I1,2) as char(1))
+Cast(dbo.fn_GetBit(@I1,1) as char(1))

--Do some Bitwise operations
PRINT dbo.fn_GetBitString( @I1 & @I2 ,4) --Bitwise AND
PRINT dbo.fn_GetBitString( @I1 | @I2 ,4) --Bitwise OR
PRINT dbo.fn_GetBitString( @I1 ^ @I2 ,4) --Bitwise XOR

By rrinchuse, 2003/03/21

Total article views: 69 | Views in the last 30 days: 2
Your response
 
 
Related tags

Miscellaneous    
T-SQL Aids    
 
Already registered?  

Free registration required

To read the rest of this article, and access thousands of other articles, we ask you to register on the site and subscribe to our newsletters.

Register

E-mail address:
Password:
Password (confirm):

  

Subscriptions

We ask you to register on the site and subscribe to our newsletters. Subscribing to our newsletters gets you:

  • ALL of our content (thousands of articles, scripts, and forum postings)
  • A daily newsletter (example)
  • A weekly news round up (example)
  • The opportunity to ask and answer questions in our forums
  • A daily Question of the Day to test and help you increase your knowledge of SQL Server.

We ask that you give the newsletter a try for a week. Over 200,000 SQL Server Professionals a day find it entertaining and useful. If not, you are welcome to unsubscribe at anytime.

Steve Jones
Editor, SQLServerCentral.com