[Haskell-beginners] Converting bytes to numbers

Chaddaï Fouché chaddai.fouche at gmail.com
Tue Mar 6 20:33:16 CET 2012


On Tue, Mar 6, 2012 at 7:47 PM, David McBride <toad3k at gmail.com> wrote:
> While I like your pre-zipping solution, I see why it didn't work out
> well for you.  The way that I've done such things is with folds.  The
> thing is that you need to store both the final answer as well as the
> index of the bytestring where you are so that the supplied function
> can know what power to take 256 to at each step.  Here's how I would
> do it.
>
> totalBS :: ByteString -> Integer
> totalBS bs = ans
>  where
>    (_,ans) = foldr' func (0,0) (BS.reverse bs)
>    func byte (acc,ans) = (acc+1, ans + fromIntegral byte * (256^acc))
>
> This should work on any size bytestring.

Rather than doing this you can simply multiply by 256 because a + 256
b + 256² c == a + 256 ( b + 256 c )

So :
> totalBS :: ByteString -> Integer
> totalBS = BS.foldr' (\byte total -> fromIntegral byte + 256 * total) 0

This is an idiom often used :)

Note that for normal sized words and if your parser become more
complicated, you should look at the binary package to parse streams of
bytes.

-- 
Jedaï



More information about the Beginners mailing list