Question

In other words, based on the ASCII table, from the range of '0' to '9',

how may I convert them into integers 0 to 9?

A solution such as:

char a = '6';
int b = a-48;

has already been floating around these parts, but I was wondering if there are other ways to go about this without the use of magic numbers?

Was it helpful?

Solution

Since '0' is not guaranteed to be 48, but the numbers are guaranteed to be consecutive, you can use a-'0'.

OTHER TIPS

If you really want to, you could use a stringstream like this:

#include <string>
#include <sstream>

int charToInt(char c) {

  // initialize a buffered stream with a 1-character string
  std::stringstream ss(std::string(1,c));

  // read an int from the stream
  int v;
  ss >> v;
  return v;

}

Not the simplest way to do the conversion, but this way you don't see any of the implementation details involving "magic" number or character. You also get error handling (an exception is thrown) if the caracter was not a number.

On the other hand, if you're absolutely certain that the character c is in the '0'..'9' range, I don't see why not use c - '0'.

Another solution is to replace c - 48 with c & 0xf, but that still involves magic numbers and is less readable than c - '0'

The ascii table is ordered in an hexadecimal way, so it's very easy to change numbers characters to real number value, or another things like to Uppercase to Lower...

As the numbers begin in the 0x30, then 0x30 =0 , 0x31 = 1, 0x32 =2, etc, you must just remove the 0x30 to get the real value.

char number='2';
int numberValue = (int)number - 0x30; /* you can rest the '0' value too */

As it, to convert an int to char is the same, just add it the 0x30.

int numberValue=5;
char number = (int)numberValue +0x30; /* or add '0' to your var */

Subtract ASCII zero from the number:

char a = '2';
int b = a-'0';

If you can't use '0', how about that kind of cheating?

(int)(a + 2) % 10;

If it's a char, not a char pointer, you can do this:

 int convert (char x)
 {
     return (int(x) - int('0'));
 }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top