I am trying to generate large random prime numbers (1024 bit-ish) so I need a way to generate large positive random numbers.
I began with System.Random but want to move to Crypto.Random from the crypto-api package.
The Crypto.Random only produces bytestrings, so I need a way to convert to an Integer type. What is the best way to do this?
Without poking around in the internals of GHC.Integer you can fold the bytestring into an Integer one byte at a time.
import qualified Data.ByteString as BS
import Data.Bits
fromBytes :: ByteString -> Integer
fromBytes = BS.foldl' f 0
where
f a b = a `shiftL` 8 .|. fromIntegral b
If you want to read Natural numbers instead of Integers you can give this a more general type signature.
-- Read bytes in big-endian order (most significant byte first)
-- Little-endian order is fromBytes . BS.reverse
fromBytes :: (Bits a, Num a) => ByteString -> a
fromBytes = BS.foldl' f 0
where
f a b = a `shiftL` 8 .|. fromIntegral b
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With