- Solution 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. So you would unpack your bytestring to a list of Word8
s and then implement addition of a base-256 number, like so:
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).
- Solution 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:
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)