Skip to content

Instantly share code, notes, and snippets.

@voidlizard
Last active December 15, 2015 03:29
Show Gist options
  • Save voidlizard/5194823 to your computer and use it in GitHub Desktop.
Save voidlizard/5194823 to your computer and use it in GitHub Desktop.
csum16 :: BS.ByteString -> Maybe Word16
csum16 s = words >>= return . rotate . trunc . (foldl' (\acc w -> acc + fromIntegral w) 0)
where withResult (Left _, _) = Nothing
withResult (Right s, _) = Just s
words = withResult $ flip runGet s (replicateM (BS.length s `div` 2) $ getWord16le)
trunc :: Word32 -> Word16
trunc w = fromIntegral $ complement $ (w .&. 0xFFFF) + (w `shiftR` 16)
rotate :: Word16 -> Word16
rotate x = x `rotateL` 8
{-# INLINE rotate #-}
{-# INLINE csum16 #-}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment