如何从 ByteString 转换为正整数

How can I convert from a ByteString to a positive Integer

我正在尝试生成大的随机质数(1024 位左右),所以我需要一种方法来生成大的正随机数。

我从 System.Random 开始,但想从 crypto-api 包转到 Crypto.Random

Crypto.Random 仅生成字节串,因此我需要一种方法来转换为 Integer 类型。最好的方法是什么?

无需深入研究 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

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

-- 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