# Base 10 arithmetic

The characters in the ascii codes have a decimal equivalent: http://www.asciitable.com/. Let's assume the decimal value of each ascii code requires to be 3 digits. So the NUL character is 000. The lower case d character is 100. And so forth. Below is an arithmetic solution to find what the middle digit will be.

(x - (100 * (x / 100))) / 10


For example, if the decimal code is 010, then the formula will work because it gives us 1, which is the middle digit:

(10 - (100 * (10 / 100))) / 10 = 1


Same thing if we plug in another decimal like 100, whose middle digit is 0:

(100 - (100 * (100 / 100))) / 10 = 0


I can easily solve for the solution, but my question is how does the arithmetic work so effectively here in getting us that middle digit? I am quite familiar with the base-10 decimal system, and I can see why we divide by 10 since the middle digit is in the 10's place, but other than that, I'm not sure how this works so effectively.

• What do you think dividing by 100 does? (Note that you are implicitly using C-style division here: 10 / 100 == 0 for your middle statement to actually work out.) – tabstop Feb 10 '14 at 23:56
• The $i$'th digit from the right in base $d$ can also be extracted with $\frac{n}{d^{i-1}}\pmod d$, if you can use the modulo ($\%$) operator. – Ragnar Feb 10 '14 at 23:57
• @tabstop yes that is true, it ignores the remainder and decimal and just keeps the quotient. – JohnMerlino Feb 10 '14 at 23:57

Your division signs are integer divisions, so $x/100$ is the hundreds digit of $x$. If $x$ could be larger than $999$, this expression would have all the digits of $x$ except the lowest two. When you do $(x-(100*(x/100))$ you are subtracting off $100$ times the hundreds digit, which leaves you with just the tens and ones digit. Another way to express this is to use $x \pmod {100}$, which is expressed in many computer languages as $x \% 100$ Now, given that you just have the lowest two digits of $x$, dividing by $10$ will get you the higher of those.

A more general approach for extracting digits is to start from the ones digit and use the modulo operator. The ones digit of $x$ is $x\%10$ The tens digit of $x$ is $(x/10)\%10$ The hundreds digit is $(x/100)\%10$ and so on.