2
votes

I'm trying to find a function that converts a Char to a Word8, and another that converts it back. I've looked on Hoogle and there are no functions of type Char -> Word8. I want to do this because Word8 has an instance of the Num class, and I would be able to add numbers to them to change them to another number. For example, my function would look something like:

shift :: Char -> Int -> Char
shift c x = toChar $ (toWord8 c) + x

Any ideas?

2

2 Answers

6
votes

You can use fromEnum and toEnum to go via Int instead. This has the added benefit of also supporting Unicode.

> toEnum (fromEnum 'a' + 3) :: Char
'd'
2
votes

I found these using FP Complete's Hoogle: http://haddocks.fpcomplete.com/fp/7.7/20131212-1/utf8-string/Codec-Binary-UTF8-String.html#v:encodeChar

A Char doesn't necessarily contain only one byte, so the conversions you're describing could lose information. Would these functions work instead?