Click here to Skip to main content
15,898,987 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a column in a table that contains integers. I am looking for a way to select only those rows that have integer powers of 2 in this column, such as 1, 2, 4, 8, 16, 32, 64, etc.

Thanks
Posted

You didn't mention the database but if you're using Sql Server 2012 then one way is to use LOG[^] function.

For example:
SQL
SELECT ...
FROM SomeTable
WHERE LOG(SomeField, 2) = ROUND(LOG(SomeField, 2), 0)

That should return all the rows where the field contains a number which is a power of 2.

A bit more explanation in Get powers of 2 with Sql Server 2012[^]
 
Share this answer
 
v2
 
Share this answer
 
Thanks Mika!

I did it using the sql server 2008 version of log. At first I was getting a type conversion error, but I ended up fixing it (somehow).

WHERE (LOG(ServiceMask) / LOG(2)) != CONVERT(int, (LOG(ServiceMask) / LOG(2)))


I found out the hard way that LOG really means LN here. So I converted to base 2.
 
Share this answer
 
Use mod, as in

where (x%2 = 0)

Oh, powers of 2. All you have is SQRT. I would probably use a temporary table containing all the numbers you want, and match values that are in that table.
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900