简体   繁体   English

你如何在 Haskell 中添加两个大的随机字节串?

[英]How do you add two large random bytestrings in Haskell?

I have two lazy bytestrings that were generated randomly using the DRBG package.我有两个使用DRBG包随机生成的惰性字节DRBG I want to interpret these bytestrings as numbers and be able to perform addition on them.我想将这些字节串解释为数字并能够对它们执行加法。 So something like a function with signature ByteString -> ByteString -> ByteString .所以就像一个带有签名的函数ByteString -> ByteString -> ByteString

In JavaScript, I was using the math-buffer package How can I do this in Haskell?在 JavaScript 中,我使用的是math-buffer包我如何在 Haskell 中做到这一点?

  1. Solution 1解决方案1

It seems that there is no math-buffer -like packages in Haskell, so you would be forced to implement these byte-wise operations yourself and use math-buffer for inspiration. Haskell 中似乎没有类似math-buffer的包,因此您将被迫自己实现这些字节操作并使用 math-buffer 来获得灵感。 So you would unpack your bytestring to a list of Word8 s and then implement addition of a base-256 number, like so:因此,您可以将字节Word8解压缩为Word8列表,然后实现以 256 为基数的数字相加,如下所示:

byteSum :: [Word8] -> [Word8] -> [Word8]
byteSum = byteSum' 0
  where
    byteSum' 0 [] [] = []
    byteSum' 1 [] [] = [1]
    byteSum' carry (x:xs) (y:ys) =
        let v = x + y + carry
        in v : byteSum' (if v < x || v < y then 1 else 0) xs ys

main = do
    let bs1 = ...
    let bs2 = ...
    let sum = pack $ byteSum (unpack bs1) (unpack bs2)

Note this is assuming little-endianness (least significant byte first).请注意,这是假设小字节序(最低有效字节在前)。

  1. Solution 2解决方案2

Alternatively, assume this bytestring is a big-endian unsigned integer, convert from ByteString -> Integer and let the Integer to the math, then convert it back:或者,假设这个字节串是一个大端无符号整数,从ByteString -> Integer转换并让 Integer 进行数学运算,然后将其转换回:

bstoi :: ByteString -> Integer
bstoi = fromDigits 0 . unpack
  where
    fromDigits n [] = n
    fromDigits n (x:xs) = fromDigits (n * 256 + (toInteger x)) xs

itobs :: Integer -> ByteString
itobs = pack . reverse . toDigits
  where
    toDigits 0 = []
    toDigits x = (fromIntegral $ x `mod` 256) : toDigits (x `div` 256)

main = do
    let bs1 = ...
    let bs2 = ...
    let sum = itobs $ (bstoi bs1) + (bstoi bs2)

import qualified Data.ByteString.Lazy as BL导入合格的 Data.ByteString.Lazy 作为 BL

pizdec bl = BL.pack . pizdec bl = BL.pack 。 BL.zipWith (+) bl BL.zipWith (+) bl

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM