Thinking outside the box

Patron Saint of Lost Yaks
posts - 203, comments - 734, trackbacks - 4

My Links

Advertisement

News

Archives

Post Categories

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

Print | posted on Saturday, August 09, 2008 1:22 PM | Filed Under [ SQL Server 2008 Algorithms SQL Server 2005 SQL Server 2000 ]

Feedback

Gravatar

# 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.
8/13/2008 7:15 AM | RamiReddy
Comments have been closed on this topic.

Powered by:
Powered By Subtext Powered By ASP.NET