Skip to content

Instantly share code, notes, and snippets.

@ijt
Created February 14, 2012 08:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ijt/1824887 to your computer and use it in GitHub Desktop.
Save ijt/1824887 to your computer and use it in GitHub Desktop.
Check that n & (n - 1) is non-zero for non-power-of-two numbers
import Data.Bits ((.&.))
import Test.QuickCheck (Property, (==>))
prop_bits :: Int -> Property
prop_bits n = n > 0 ==> intToBool (n .&. (n - 1)) == not (isPowerOfTwo n)
intToBool 0 = False
intToBool _ = True
isPowerOfTwo :: Int -> Bool
isPowerOfTwo x = fromIntegral (truncate l2) == l2
where l2 = log xf / log 2
xf = fromIntegral x
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment