2011-03-08 12 views
17

Je me demande comment je peux convertir un Char en un Int. E.g.Convertir Char en Int

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

Mais je suis pas idée:/

Merci à l'avance

+9

Découvrez et utilisez [hoogle] (http://www.haskell.org/hoogle/?hoogle=Char+-%3E+Int). –

Répondre

21

Vous pouvez utiliser la fonction ord pour convertir un caractère à sa représentation entière (ordinal).

chr va dans l'autre direction.

> ord '\x2'­ 
    => 2 
> chr 97 
    => 'a' 
> ord (chr 42) 
    => 42 
+19

juste pour ajouter, vous devez 'importer Char' ou' importer Data.Char' afin d'utiliser ceux – newacct

4

Vous pouvez utiliser fromEnum ou Data.Char.ord.

+0

(fromEnum 'x') - (fromEnum '0') == x – jpredham

+1

@jpredham Nous avons 'digitToInt '9 ''de' Data.Char' pour ce puprose exact – gvlasov