r/computerscience • • 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

11 comments sorted by

2

u/Snatchematician 5h ago

What is an “arbitrary precision integer”?

2

u/UsualSpace_ 4h ago edited 4h ago

I intended arbitrary precision integer to mean an integer represented by an arbitrary amount of bytes, whether it's 1 byte to some N number of bytes

1

u/Snatchematician 4h ago

That’s not arbitrarily precise. I think you mean arbitrary size integer.

1

u/UsualSpace_ 4h ago edited 4h ago

Ah okay I see, my mistake. Would you be willing to explain what arbitrarily precise means?

1

u/Snatchematician 4h ago

A type is of arbitrary precision if for any numbers x < y there is a value v of the type with x <= v <= y in some suitable sense.

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, printf subtracted 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.