Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cast [Int] to [Word8]

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

like image 946
user668074 Avatar asked Nov 08 '15 17:11

user668074


2 Answers

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 Ints, there's not much you can do besides paying the cost of conversion. Ints 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 Word8s in the first place.

like image 122
hao Avatar answered Oct 26 '22 22:10

hao


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.

like image 7
sinan Avatar answered Oct 27 '22 00:10

sinan