Peter Larsson Blog

Patron Saint of Lost Yaks

How to tell if a number is a "POWER of 2"-number

SELECT  Number,
        1 - SIGN(Number & (Number - 1))
FROM    master..spt_values
WHERE   Type = 'P'
        AND Number > 0

 

Other way is

 

CREATE FUNCTION dbo.isPowerOf2
(
      @i INT
)
RETURNS BIT
AS
BEGIN
      DECLARE @x FLOAT 
 
      SET @x = LOG(Number) / LOG(2)

      RETURN      CASE
                  WHEN FLOOR(@x) = CEILING(@x) THEN 1
                  ELSE 0
            END
END

Legacy Comments


RamiReddy
2008-08-13
re: How to tell if a number is a "POWER of 2"-number
Is that first query will work for the number
524288 which is 2 power 19. it will not work for that number. that query has a limitation. it will work only for the values which are in that table. table records are finite. but 2 power numbers are infinite.