Last active
May 22, 2020 18:00
-
-
Save rcythr/e55f7de9d6507a2661dca56cc9698ca6 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| 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