# Bitmap an Integer Value

,

Do you hate using bitwise operands?  I do, a lot.  I wrote the following function to try to minimize the need for using them.  When testing 'status' variables in the 'sysobjects' table, for example, I decided there just had to be an easier way to see if bit 31 is set than asking if STATUS & 0x40000000  0.

There is now, using the following function:

IF dbo.f_bitmap (STATUS) LIKE '_1%'

The function accepts an integer (INT) value and returns a 32-char string consisting of '1's and '0's, representing (from left to right) the high order bit (32) and low order bit (1) settings of the integer.

Example:  Determine if bit 19 of an integer variable is set.

IF RIGHT (dbo.f_bitmap (@integer), 19) LIKE '1%'
PRINT 'BIT 19 is set!'
ELSE
PRINT 'BIT 19 is not set'

```CREATE FUNCTION dbo.f_bitmap (@f_int INT)
RETURNS CHAR (32)
/*
||======================================================================
|| Date written:  3/6/2003 (Dise)
||
|| Description:  This scalar function accepts a four-byte integer value
|| and returns a 32-char string, in '0's and '1's, representing its
|| bit pattern.
||======================================================================
*/AS
BEGIN
/*
||====================================================================
|| Facts:
||   1.  If the integer is negative, BIT 32 (leftmost bit) is set.
||   2.  For each remaining bit (n = 31 to 1), if bitwise ANDing the
||       integer value with 2^(n - 1) is not zero, then the bit is
||       set.
||====================================================================
*/  DECLARE @bit  CHAR (1)
, @bits VARCHAR (32)
, @pos  INT

SELECT @bits = ''
, @pos  = 32

WHILE @pos > 0
BEGIN
SELECT @bit  = CASE
WHEN (@pos = 32
AND @f_int                        < 0)
OR (@pos < 32
AND @f_int & POWER (2, @pos - 1) != 0)
THEN '1'
ELSE '0'
END
, @bits = @bits + @bit
, @pos  = @pos  - 1
END

RETURN @bits
END```

## Rate

You rated this post out of 5. Change rating

## Rate

You rated this post out of 5. Change rating