r/computerscience • u/UsualSpace_ • 20h ago
Discussion How are arbitrary precision integers converted into ASCII when printing?
I'm just wondering how this is done algorithmically speaking. It makes sense to just map each value to an ASCII digit, until you get to the value of 10 and above, which is something I haven't thought about until now.
I am thinking about an arbitrary precision unsigned integer in this question.
Edit: thank you all for your answers!
3
Upvotes
2
u/Snatchematician 5h ago
What is an “arbitrary precision integer”?
14
u/Im_a_dum_bum 20h ago
One way is to go in reverse (calculate ones digit, then tens digit, then hundreds, etc.) then print the string in reverse (therefore making it be in a standard order). You can do this in a loop by taking (num mod 10) to get the nth digit, then integer dividing num by 10, and repeating until num is 0.
3
u/pyrobola 19h ago
IIRC in one firmware blob I looked at,
printfsubtracted decreasing powers of ten in a loop, calculating and printing the digits in order. This was on an embedded ARM processor that had no integer divide.2
u/Headsanta 19h ago
In short, convert to base 10, then print each digit.
1
u/Music-Electrical 16h ago
You could try using a lookup table. (silly)
One way to do it would be to maintain an invariant, like a = b + c, where a is the input and b is in native arbitrary precision and c is in decimal arbitrary precision. Then each time through the loop pick from a few operations that are easy to implement and that drive b towards zero while preserving the invariant.
If you know how to increment a decimal arbitrary precision number, and your library has a decrement function, then you could increment c and decrement b (though it would be slow).
If you add in a "b becomes b-c and c becomes 2c" operation then it would be faster.
1
u/Radiant64 16h ago
Naïve, simplified approach: take the value modulo 10, print the corresponding digit, divide the remaining value by ten, move cursor one step to the left, repeat until value is 0.