0

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

  • plenty of results on [Hoogle](https://hoogle.haskell.org/?hoogle=String%20-%3E%20ByteString). (You most likely want the first-listed one, `pack`.) – Robin Zigmond Dec 29 '21 at 14:48
  • @RobinZigmond pack creates bytestring from string. In my case ``unpack $ pack "72 97 115 107 104 101 108 108"`` will result in "72 97 115 107 104 101 108 108". I want to ``unpack $ functionIWant "72 97 115 107 104 101 108 108"`` result in "Haskhell" – someone1231 Dec 29 '21 at 15:14
  • 1
    oh, so your string is actually a stringified sequence of space-separated ascii numeric values that you want to convert to a (byte)string? That's a rather strange format, but it should be simple enough to do - why don't you show what you've tried? – Robin Zigmond Dec 29 '21 at 15:24
  • 3
    Split on spaces with `words`, use `read` on each element to get an `Int`, then convert each to a `Char` with `chr` or `toEnum`. You don't need `ByteString` for this. – Aplet123 Dec 29 '21 at 15:47
  • 2
    What should happen to `"206 155"`? (In other words, what is your relationship with encodings here?) – Daniel Wagner Dec 29 '21 at 19:20

1 Answers1

5

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"
Daniel Wagner
  • 145,880
  • 9
  • 220
  • 380