Created
May 23, 2020 13:25
-
-
Save rcythr/26d07031b6d023271343a5707a06a2d0 to your computer and use it in GitHub Desktop.
Computes 64bit parity of the given file.
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 qualified Data.ByteString as BS | |
| import qualified Data.ByteString.Unsafe as BS | |
| import Data.Word | |
| import Data.Bits | |
| import Foreign.C.String | |
| import Foreign.Ptr | |
| import Foreign.Storable | |
| import System.Environment (getArgs) | |
| parity64' :: CStringLen -> IO Word64 | |
| parity64' (cptr, clen) = do | |
| let (wlen,wrem) = clen `divMod` 8 | |
| parity <- foldM (\s o -> peek (cptr `plusPtr` o) >>= (\v -> return $ s `xor` v)) 0 [0, 8 .. 8*wlen] | |
| parity' <- peek (cptr `plusPtr` (8*wlen-(8-wrem))) | |
| return $ parity `xor` (parity' `shiftL` (8*(8-wrem))) | |
| parity64 :: BS.ByteString -> IO Word64 | |
| parity64 bs = BS.unsafeUseAsCStringLen bs parity64' | |
| main = do | |
| args <- getArgs | |
| content <- BS.readFile (head args) | |
| print =<< parity64 content |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment