r/computerscience • u/UsualSpace_ • 6d 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!
14
Upvotes
4
u/Snatchematician 5d ago
What is an “arbitrary precision integer”?
20
u/Im_a_dum_bum 6d 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.
6
u/pyrobola 6d 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.3
u/sneakyruds 3d ago
What you're looking for is radix conversion. Knuth covers it in section 4.4 of volume 2 of the Art of Computer Programming. https://flintlib.org/doc/algorithms/integers/radix-conversion.html describes how it is done efficiently in the flint library, though the explanation is quite terse. Hopefully those pointers are enough to get you started!
2
u/Radiant64 6d 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.
2
u/Fizzelen 3d ago
This is the type of question that leads to rabbit holes, be wary it will cost you time and you will probably learn a lot of interesting and functionally useless information. The final boss is doing it in assembly using a basic computer like Chip8
1
u/Music-Electrical 6d 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/am_Snowie 4d ago
Since they're stored in memory, you can loop through it i guess.
1
u/Headsanta 6d ago
In short, convert to base 10, then print each digit.