Search code examples
low-levelnumber-formatting

Print a number in decimal


Well, it is a low-level question Suppose I store a number (of course computer store number in binary format) How can I print it in decimal format. It is obvious in high-level program, just print it and the library does it for you.

But how about in a very low-level situation where I don't have this library. I can just tell what 'character' to output. How to convert the number into decimal characters?

I hope you understand my question. Thank You.


Solution

  • There are two ways of printing decimals - on CPUs with division/remainder instructions (modern CPUs are like that) and on CPUs where division is relatively slow (8-bit CPUs of 20+ years ago).

    The first method is simple: int-divide the number by ten, and store the sequence of remainders in an array. Once you divided the number all the way to zero, start printing remainders starting from the back, adding the ASCII code of zero ('0') to each remainder.

    The second method relies on the lookup table of powers of ten. You define an array of numbers like this:

    int pow10 = {10000,1000,100,10,1}
    

    Then you start with the largest power, and see if you can subtract it from the number at hand. If you can, keep subtracting it, and keep the count. Once you cannot subtract it without going negative, print the count plus the ASCII code of zero, and move on to the next smaller power of ten.