Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 659
user668074 Avatar asked Nov 01 '17 07:11

user668074


1 Answers

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
like image 200
Cirdec Avatar answered Nov 09 '22 10:11

Cirdec