Last active
March 1, 2024 06:48
-
-
Save thelissimus/11110347d2a49a9bd8c6f0e6936a76bd to your computer and use it in GitHub Desktop.
Bit-packing Word32 and Word8 into Word64 in Haskell.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Data.Bits (Bits (shiftL, shiftR, (.&.), (.|.))) | |
import Data.Word (Word32, Word64, Word8) | |
word64 :: (Word32, Word8) -> Word64 | |
word64 (w32, w8) = ((fromIntegral w32 :: Word64) `shiftL` 8) .|. (fromIntegral w8 :: Word64) | |
{-# INLINE [0] word64 #-} | |
unword64Fst :: Word64 -> Word32 | |
unword64Fst w = fromIntegral (w `shiftR` 8) | |
{-# INLINE [0] unword64Fst #-} | |
unword64Snd :: Word64 -> Word8 | |
unword64Snd w = fromIntegral (w .&. 255) | |
{-# INLINE [0] unword64Snd #-} | |
unword64 :: Word64 -> (Word32, Word8) | |
unword64 w = (unword64Fst w, unword64Snd w) | |
{-# INLINE [0] unword64 #-} | |
{-# RULES | |
"bit_pack_cancel" forall a b. unword64 (word64 (a, b)) = (a, b) | |
"bit_unpack_fst" forall a. fst (unword64 a) = unword64Fst a | |
"bit_unpack_snd" forall a. snd (unword64 a) = unword64Snd a | |
#-} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment