]> gitweb @ CieloNegro.org - wavpack.git/blobdiff - Codec/Audio/WavPack/Internal.hs
new function: countBits
[wavpack.git] / Codec / Audio / WavPack / Internal.hs
index b852a76c74078f41e6260041de7ec853ae5deb78..5769a3fac37f202ab813a0f4074d467b3e6610d6 100644 (file)
@@ -12,6 +12,8 @@ module Codec.Audio.WavPack.Internal
 
     , exp2s
     , exp2
+
+    , countBits
     )
     where
 import Data.Int
@@ -35,7 +37,7 @@ packWeight !w
         fromIntegral w'''
 
 -- | Convert a packed weight to internal weight (+/-1024). Note that
--- the following equation might not hold because 'packWeight' is
+-- the following equation /might not hold/ because 'packWeight' is
 -- lossy.
 --
 -- > unpackWeight . packWeight = id
@@ -70,7 +72,7 @@ log2s !n
 -- zero and can therefore represent both zero and negative
 -- values. They have 8 bits of precision and in \"roundtrip\"
 -- conversions the total error never exceeds 1 part in 225 except for
--- the cases of +/-115 and +/-195 (which error by 1).
+-- the cases of +\/-115 and +\/-195 (which error by 1).
 --
 -- This function returns the log2 for the specified 32-bit unsigned
 -- value. The maximum value allowed is about 0xff800000 and returns
@@ -123,6 +125,15 @@ exp2 !l
         else
             exp2l `shiftL` fromIntegral (l' - 9)
 
+-- | 'countBits' @av@ returns the number of bits that is required to
+-- represent @av@.
+countBits ∷ Word32 → Word8
+countBits av
+    | av < (1 `shiftL`  8) = getNBits (fromIntegral  av)
+    | av < (1 `shiftL` 16) = getNBits (fromIntegral (av `shiftR`  8)) +  8
+    | av < (1 `shiftL` 24) = getNBits (fromIntegral (av `shiftR` 16)) + 16
+    | otherwise            = getNBits (fromIntegral (av `shiftR` 24)) + 24
+
 getNBits ∷ Word8 → Word8
 getNBits = UV.unsafeIndex nbitsTable ∘ fromIntegral
     where