How can I convert from a ByteString to a positive integer

I am trying to create large random primes (1024 bits), so I need a way to generate large positive random numbers.

I started with System.Random , but want to switch to Crypto.Random from the crypto-api package.

Crypto.Random only creates tags, so I need a way to convert to an Integer type. What is the best way to do this?

+5
source share
1 answer

Without scrolling in the internal elements of GHC.Integer you can add a bytestring in Integer one byte at a time.

 import qualified Data.ByteString as BS import Data.Bits fromBytes :: ByteString -> Integer fromBytes = BS.foldl' f 0 where fab = a `shiftL` 8 .|. fromIntegral b 

If you want to read Natural numbers instead of Integer , 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 fab = a `shiftL` 8 .|. fromIntegral b 
+3
source

Source: https://habr.com/ru/post/1273040/


All Articles