How can I cast an int list, [Int]
into a Word8 list, [Word8]
. I can cast a single int using let a = 1 :: Word8
. How can I do the same for a list of integers values? When I try I get an error.
(Aside, my main goal is to convert from [Int] -> ByteString
, I'm using [Word8]
as an intermediate, is there a better way to do this?)
Try fromIntegral
, the Swiss-army tool of converting between integer types: Data.ByteString.pack (map fromIntegral [97..97 + 25])
should yield "abcdefghijklmnopqrstuvwxyz" :: Data.ByteString
.
As for the question of whether this is the best way: once you have a list of Int
s, there's not much you can do besides paying the cost of conversion. Int
s are 32-bit machine integers with three bits reserved for tagging (I think), whereas Word8
are 8-bit machine integers. If performance is an issue, perhaps only use Word8
s in the first place.
For converting between different numeric types, use fromIntegral
. In your case you need map fromIntegral
. Note that you may need to specify some types if from your program it's not possible to infer return type of fromIntegral
.
For generating ByteString
, try: Data.ByteString.pack . map fromIntegral
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With