Programmers often need to write integers as characters. Thus given the 32-bit value 1234, you might need a function that writes the characters 1234. W

Apple M1 vs AMD Zen2 for binary to ASCII conversion

submited by
Style Pass
2021-05-19 02:51:46

Programmers often need to write integers as characters. Thus given the 32-bit value 1234, you might need a function that writes the characters 1234. We can use the fact that the ASCII numeral characters are in sequence in the ASCII table: ‘0’+0 is ‘0’, ‘0’+1 is ‘1’ and so forth. With this optimization in mind, the standard integer-to-string algorithm looks as follow:

This algorithm writes the digits in reverse. So actual C/C++ code will write a pointer that you decrement (and not increment):

You can bound the size of the string (10 characters for 32-bit integers, 20 characters for 64-bit integers). If you have signed integers, you can detect the sign initially and make the integer value non-negative, write out the digits and finish with the sign character if needed. If you know that your strings are long, you can do better by writing out the characters two at a time using lookup tables.

If you look at the main loop, and pay only attention to the critical data dependency, you divide your numerator by 10, then you check its value, and so forth. So your performance is bounded by the speed at which you can divide the numerator by 10.

Leave a Comment