Skip to content

Instantly share code, notes, and snippets.

@rcythr
Last active May 22, 2020 18:00
Show Gist options
  • Select an option

  • Save rcythr/e55f7de9d6507a2661dca56cc9698ca6 to your computer and use it in GitHub Desktop.

Select an option

Save rcythr/e55f7de9d6507a2661dca56cc9698ca6 to your computer and use it in GitHub Desktop.
module Main where
import Control.Monad
import Data.Array
import Data.Array.ST
import Data.Bits
import qualified Data.ByteString as BS
import Data.Word
import System.Environment (getArgs)
crc32Polynomial :: Word32
crc32Polynomial = 0xEDB88320
crc32Table :: Array Word32 Word32
crc32Table = runSTArray $ do
arr <- newArray (0,255) 0
forM_ [1..255] $ \i -> do
writeArray arr i i
forM_ [0..7] $ \_ -> do
crc <- readArray arr i
if (crc .&. 1) == 1 then
writeArray arr i ((crc `shiftR` 1) `xor` crc32Polynomial)
else
writeArray arr i (crc `shiftR` 1)
return arr
crc32 :: BS.ByteString -> Word32
crc32 = complement . BS.foldl (\crc b -> (crc `shiftR` 8) `xor` crc32Table ! ((crc .&. 0xFF) `xor` (fromIntegral b))) (complement 0)
main = do
args <- getArgs
content <- BS.readFile (head args)
print $ crc32 content
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment