Search code examples
haskellbytestring

Creating ByteString from String representation of chars in Haskell


I'm trying to create Char8 ByteString from String of already converted to bytes Chars.

For example for String "65" I want ByteString on which unpack method will give me "A". Because 65 is equal to chr 65. It would be better if this method will able to work with digits in hex representation. So I want something like this:

toByteString :: String -> ByteString
toByteString s = **** s

--Numbers bettwen 0 and 255 or 00 and ff
someBS = toByteString " 72 97 115 107 104 101 108 108" -- evaluates to ByteString

str :: String
str bs = unpack someBS -- evaluates to "Haskhell" 

I already tried to find something what I want in documentation for ByteString.Char8 and Char, but it seems that there is no built in methods for my purpose in these libraries. Maybe I'm missing something.

I think there is must be a way to create ByteString from chars and somehow it's not obvious enough to find it


Solution

  • Don't start from a String, if you can help it. For example, native Haskell syntax already supports numbers in both decimal and hexadecimal:

    Data.ByteString> pack [72, 97, 115, 107, 104, 101, 108, 108]
    "Haskhell"
    Data.ByteString> pack [0x48, 0x61, 0x73, 0x6b, 0x68, 0x65, 0x6c, 0x6c]
    "Haskhell"
    

    If you must start from String, any parser combinator library will work fine for getting you from " 72 97 115" to [72, 97, 115] -- or even just map read . words.

    > import qualified Data.ByteString as BS
    BS> BS.pack . map read . words $ " 72 97 115 107 0x68 0x65 0x6c 0x6c"
    "Haskhell"