Search code examples
haskellbytestring

How can I convert from a ByteString to a positive Integer


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?


Solution

  • 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