newbie C syntax help

Hi All, I am a noob.

I was playing around with the servo example and came across this code.

switch(ch) { case '0'...'9': v = v * 10 + ch - '0'; break;

Can anyone explain why is it necessay to have '0' to get the correct input v from the serial port?

Because char from '0' to '9' have binary values from 48 to 57. If you want to effectively add the numeric value you need to subtract '0' or 48 without quote. i.e: char '5' equals 53 in binary if you subtract 48 or '0' from 53 you will get the binary value 5 (53- 48 = 5), which is what you need in your v = v * 10 + ch - '0'; expression. It would be the same as v = v * 10 + 5.

You are turning an ASCII character into a numerical digit. For example, the ASCII value of '0' is 48, the value of '1' is 49, ..., and the value of '9' is 57.

If you don't subtract off the '0', your calculation ends up being:

v = v * 10 + ch = v * 10 + 50 if ch is '2', which is clearly wrong

When we stick in the "- '0'", we end up with:

v = v * 10 + ('2' - '0') = v * 10 + 50 - 48 = v * 10 + 2

So we have successfully converted '2' into 2, as desired.

  • Ben

Because char from ‘0’ to ‘9’ have binary values from 48 to 57. If you want to effectively add the numeric value you need to subtract ‘0’ or 48 without quote. i.e: char ‘5’ equals 53 in binary if you subtract 48 or ‘0’ from 53 you will get the binary value 5 (53- 48 = 5), which is what you need in your v = v * 10 + ch - ‘0’; expression. It would be the same as v = v * 10 + 5.

To be slightly nit-picky in the effort of achieving clearer communication, char ‘5’ equals 53 in decimal. What’s important is that it’s a numerical value, not that it be in a specific base. Binary literally means a base-two representation of a numerical value.

  • Ben

thx, it is all clear now.

Because char from '0' to '9' have binary values from 48 to 57. If you want to effectively add the numeric value you need to subtract '0' or 48 without quote. i.e: char '5' equals 53 in binary if you subtract 48 or '0' from 53 you will get the binary value 5 (53- 48 = 5), which is what you need in your v = v * 10 + ch - '0'; expression. It would be the same as v = v * 10 + 5.

To be slightly nit-picky in the effort of achieving clearer communication, char '5' equals 53 in decimal. What's important is that it's a numerical value, not that it be in a specific base. Binary literally means a base-two representation of a numerical value.

  • Ben

You are right.