Skip to content

Instantly share code, notes, and snippets.

@axman6
Created December 23, 2014 04:39
Show Gist options
  • Save axman6/6db2acd1b70d5a81c9e5 to your computer and use it in GitHub Desktop.
Save axman6/6db2acd1b70d5a81c9e5 to your computer and use it in GitHub Desktop.
log2 Word64 and count leading zeros
{-# LANGUAGE BangPatterns #-}
import Data.Bits
import Data.Word
nlz :: Word64 -> Int
nlz x = go x x 0 where
go !x !y !n
| x < 0 = n
| y == 0 = 64 - n
| otherwise = go (shiftL x 1) (shiftR y 1) (n+1)
log2 :: Word64 -> Int
log2 x = 63 - nlz x
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment