Haskell How to convert Char to Word8

14,071

Solution 1

The Data.ByteString.Char8 module allows you to treat Word8 values in the bytestrings as Char. Just

import qualified Data.ByteString.Char8 as C

then refer to e.g. C.split. It's the same bytestring under the hood, but the Char-oriented functions are provided for convenient byte/ascii parsing.

Solution 2

In case you really need Data.ByteString (not Data.ByteString.Char8), you could do what Data.ByteString itself does to convert between Word8 to Char:

import qualified Data.ByteString as BS
import qualified Data.ByteString.Internal as BS (c2w, w2c)

main = do
    input <- BS.getLine
    let xs = BS.split (BS.c2w ' ') input 
    return ()

Solution 3

People looking for a simple Char -> Word8 with base library:

import Data.Word

charToWord8 :: Char -> Word8
charToWord8 = toEnum . fromEnum

Solution 4

I want to directly address the question in the subject line, which led me here in the first place.

You can convert a single Char to a single Word8 with fromIntegral.ord:

λ> import qualified Data.ByteString as BS
λ> import Data.Char(ord)

λ> BS.split (fromIntegral.ord $ 'd') $ BS.pack . map (fromIntegral.ord) $ "abcdef"

["abc","ef"]

Keep in mind that this conversion will be prone to overflows as demonstrated below.You have to assure that your Char fits in 8 bits, if you do not want this to occur.

λ> 260 :: Word8

4

Of course, for your particular problem, it is preferable to use the Data.ByteString.Char8 module as already pointed out in the accepted answer.

Share:
14,071

Related videos on Youtube

Andrew
Author by

Andrew

http://twitter.com/proglog

Updated on June 04, 2022

Comments

  • Andrew
    Andrew almost 2 years

    I want to split ByteString to words like so:

    import qualified Data.ByteString as BS
    
    main = do
        input <- BS.getLine
        let xs = BS.split ' ' input 
    

    But it appears that GHC can't convert a character literal to Word8 by itself, so I got:

    Couldn't match expected type `GHC.Word.Word8'
                with actual type `Char'
    In the first argument of `BS.split', namely ' '
    In the expression: BS.split ' ' input
    

    Hoogle doesn't find anything with type signature of Char -> Word8 and Word.Word8 ' ' is invalid type constructor. Any ideas on how to fix it?

    • Daniel Wagner
      Daniel Wagner almost 12 years
      Don't use ByteString for text! Use Text instead.
    • Don Stewart
      Don Stewart almost 12 years
      Text is unicode-friendly, so your strings will be strings in all countries. ByteString is for binary parsing, raw memory access, and can't handle anything other than ascii or latin1.
  • Hussein AIT LAHCEN
    Hussein AIT LAHCEN about 5 years
    I have no clue my friend