24

I need to convert a Char to an Int in Haskell? For example:

a = '\x2' -- a == 2
          -- type of a should be Char
b = charToInt a -- b == 2
                -- type of b should be Int

How can I achieve this?

1
  • 11
    Discover and use hoogle. Commented Mar 8, 2011 at 0:24

2 Answers 2

30

You can use the ord function to convert a character to its integer (ordinal) representation.

chr goes the other direction.

> ord '\x2'­
  => 2
> chr 97
  => 'a'
> ord (chr 42)
  => 42
Sign up to request clarification or add additional context in comments.

1 Comment

just to add, you have to import Char or import Data.Char in order to use those
5

You can use fromEnum or Data.Char.ord.

2 Comments

(fromEnum 'x') - (fromEnum '0') == x
@jpredham We have digitToInt '9' from Data.Char for that exact puprose

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.