h1

C++: Convert a “char” digit into an “int” digit

February 9, 2012

Nothing special. It’s just a one-line function that builds on the concept that chars are, well, also integers. To be more specific, they are integer ASCII codes.

//returns an int from a number literal
int castInt(char src) {
return src - 48;
}

According to this, the digits from 0-9 have codes from 0x30 to 0x39 in hex, which is 48 to 57 in decimal. What were doing is subtracting 48 from the supplied char parameter’s ASCII code to obtain a digit from 0-9.

Note that this code was intended to be a simple and quick fix and as such has many loopholes and flaws, one of which is the inability to check if the supplied parameter was actually a digit or not. Nevertheless, it could be useful in small programs, such as console prompts (“Press 1 to continue, 2 to exit…”);

Well, that’s a load of text for one C++ function.

2 comments

  1. Though still code page dependent, you can use the clearer form:

    return src – ‘0’;


    • Yes of course, that’s a good alternative. 😀

      It’d probably be up to personal preference which one to use. 🙂



Comments are closed.

%d bloggers like this: