How do you convert char numbers to decimal and back or convert ASCII 'A'-'Z'/'a'-'z' to letter offsets 0 for 'A'/'a' …?

后端 未结 4 832
无人共我
无人共我 2020-12-07 05:20

If you have a char that is in the range \'0\' to \'9\' how do you convert it to int values of 0 to 9

And then how do you convert it back?

Also given letters

4条回答
  •  囚心锁ツ
    2020-12-07 05:47

    If you know a character c is either a letter or number, you can just do:

    int cton( char c )
    {
      if( 'a' <= c ) return c-'a';
      if( 'A' <= c ) return c-'A';
      return c-'0';
    }
    

    Add whatever error checking on c is needed.

    To convert an integer n back to a char, just do '0'+n if you want a digit, 'A'+n if you want an uppercase letter, and 'a'+n if you want lowercase.

    Note: This works for ASCII (as the OP is tagged.) See Pete's informative comment however.

提交回复
热议问题