RosettaCodeData/Task/CRC-32/Haskell/crc-32-1.hs

27 lines
719 B
Haskell
Raw Permalink Normal View History

2019-09-12 10:33:56 -07:00
import Data.Bits ((.&.), complement, shiftR, xor)
import Data.Word (Word32)
import Numeric (showHex)
2014-04-02 16:56:35 +00:00
crcTable :: Word32 -> Word32
2019-09-12 10:33:56 -07:00
crcTable = (table !!) . fromIntegral
where
table = ((!! 8) . iterate xf) <$> [0 .. 255]
shifted x = shiftR x 1
xf r
| r .&. 1 == 1 = xor (shifted r) 0xedb88320
| otherwise = shifted r
2014-04-02 16:56:35 +00:00
charToWord :: Char -> Word32
2019-09-12 10:33:56 -07:00
charToWord = fromIntegral . fromEnum
2014-04-02 16:56:35 +00:00
calcCrc :: String -> Word32
2019-09-12 10:33:56 -07:00
calcCrc = complement . foldl cf (complement 0)
where
cf crc x = xor (shiftR crc 8) (crcTable $ xor (crc .&. 0xff) (charToWord x))
2014-04-02 16:56:35 +00:00
2019-09-12 10:33:56 -07:00
crc32 :: String -> String
crc32 = flip showHex [] . calcCrc
2014-04-02 16:56:35 +00:00
2019-09-12 10:33:56 -07:00
main :: IO ()
2014-04-02 16:56:35 +00:00
main = putStrLn $ crc32 "The quick brown fox jumps over the lazy dog"