简体   繁体   中英

Haskell: Function that converts Char to Word8

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?

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'

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM