1

I am new to C and I was looking for a custom function in C that would convert a string to an integer and I came across this algorithm which makes perfect sense except for one part. What exactly is the -'0' doing on this line n = n * 10 + a[c] - '0';?

 int toString(char a[]) { int c, sign, offset, n; if (a[0] == '-') { // Handle negative integers sign = -1; } if (sign == -1) { // Set starting position to convert offset = 1; } else { offset = 0; } n = 0; for (c = offset; a[c] != '\0'; c++) { n = n * 10 + a[c] - '0'; } if (sign == -1) { n = -n; } return n; } 

The algorithm did not have an explanation from where I found it, here.

2
  • 1
    See asciitable.com - note the relation (and values) of the digit characters Commented Sep 27, 2014 at 23:22
  • No, the character '0' has the value of 48, '\0' is 0 is NUL. Commented Sep 27, 2014 at 23:28

2 Answers 2

4

The reason subtracting '0' works is that character code points for decimal digits are arranged sequentially starting from '0' up, without gaps. In other words, the character code for '5' is greater than the character code for '0' by 5; character code for '6' is greater than the character code for '0' by 6, and so on. Therefore, subtracting the code of zero '0' from a code of another digit produces the value of the corresponding digit.

This arrangement is correct for ASCII codes, EBSDIC, UNICODE codes of decimal digits, and so on. For ASCII codes, the numeric codes look like this:

'0' 48 '1' 49 '2' 50 '3' 51 '4' 52 '5' 53 '6' 54 '7' 55 '8' 56 '9' 57 
Sign up to request clarification or add additional context in comments.

Comments

2

Assuming x has a value in the range between '0' and '9', x - '0' yields a value between 0 and 9. So x - '0' basically converts a decimal digits character constant to its numerical integer value (e.g., '5' to 5).

C says '0' to '9' are implementation defined values but C also guarantees '0' to '9' to be sequential values.

2 Comments

Sorry, I'm not understanding this still and is x, n in this case?
@Bridenstine here x would be a[c] in your program

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.