如何从ByteString转换为正整数

use*_*074 6 haskell bytestring

我试图生成大的随机素数(1024 bit-ish)所以我需要一种方法来生成大的正随机数.

我开始System.Random但想要Crypto.Randomcrypto-api包中移动.

Crypto.Random只生产字节串,所以我需要一种方法来转换为Integer类型.做这个的最好方式是什么?

Cir*_*dec 5

如果不在内部进行调整GHC.Integer,可以将字节字符串一次折叠成Integer一个字节.

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
Run Code Online (Sandbox Code Playgroud)

如果你想读取Natural数字而不是Integers,你可以给它一个更通用的类型签名.

-- 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
Run Code Online (Sandbox Code Playgroud)