What is the best way to convert a String to a ByteString in Haskell?
My gut reaction to the problem is
import qualified Data.ByteString as B import Data.Char (ord) packStr = B.pack . map (fromIntegral . ord)
But this doesn't seem satisfactory.
When it is required to convert a string into a tuple, the 'map' method, the 'tuple' method, the 'int' method, and the 'split' method can be used. The map function applies a given function/operation to every item in an iterable (such as list, tuple). It returns a list as the result.
The bytes() method is an inbuilt function that can be used to convert objects to byte objects. The bytes take in an object (a string in our case), the required encoding method, and convert it into a byte object. The bytes() method accepts a third argument on how to handle errors.
The simplest way to do so is using parseByte() method of Byte class in java.
How to convert String to byte[] in Java? In Java, we can use str. getBytes(StandardCharsets. UTF_8) to convert a String into a byte[] .
Here is my cheat sheet for Haskell String/Text/ByteString strict/lazy conversion assuming the desired encoding is UTF-8. The Data.Text.Encoding library has other encodings available.
Please make sure to not write (using OverloadedStrings):
lazyByteString :: BL.ByteString lazyByteString = "lazyByteString ä ß" -- BAD!
This will get encoded in an unexpected way. Try
lazyByteString = BLU.fromString "lazyByteString ä ß" -- good
instead.
String literals of type 'Text' work fine with regard to encoding.
Cheat sheet:
import Data.ByteString.Lazy as BL import Data.ByteString as BS import Data.Text as TS import Data.Text.Lazy as TL import Data.ByteString.Lazy.UTF8 as BLU -- from utf8-string import Data.ByteString.UTF8 as BSU -- from utf8-string import Data.Text.Encoding as TSE import Data.Text.Lazy.Encoding as TLE -- String <-> ByteString BLU.toString :: BL.ByteString -> String BLU.fromString :: String -> BL.ByteString BSU.toString :: BS.ByteString -> String BSU.fromString :: String -> BS.ByteString -- String <-> Text TL.unpack :: TL.Text -> String TL.pack :: String -> TL.Text TS.unpack :: TS.Text -> String TS.pack :: String -> TS.Text -- ByteString <-> Text TLE.encodeUtf8 :: TL.Text -> BL.ByteString TLE.decodeUtf8 :: BL.ByteString -> TL.Text TSE.encodeUtf8 :: TS.Text -> BS.ByteString TSE.decodeUtf8 :: BS.ByteString -> TS.Text -- Lazy <-> Strict BL.fromStrict :: BS.ByteString -> BL.ByteString BL.toStrict :: BL.ByteString -> BS.ByteString TL.fromStrict :: TS.Text -> TL.Text TL.toStrict :: TL.Text -> TS.Text
Please +1 Peaker's answer, because he correctly deals with encoding.
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