Integer->String conversion in C/C++
I had cause of late to convert an integer into a string in C. My research indicated that there was no standardized function to do this, and thus the most portable thing to do was to write my own algorithm. After fiddling with numbers and masks and such things, I came up with the following core algorithm:
#define CONVERT_DIGIT(mask, n, offset) (( n/mask - ( n/(mask*10))*10) + offset )
This algorithm may not be as efficient as it could be, but I’m fairly happy with it given that normally I dodge anything with even a distant correlation to mathematics as if it were the plague. mask is a power of your number system base b; most of the time, this is going to be a power of 10. n is the number you want to convert. offset is used to offset the resulting integer to an ASCII equivalent; this could actually be hard-coded as 48.
Given that the number of digits in n is L, you need to initialize mask to bL-1. Then run a loop that for each digit in n runs CONVERT_DIGIT( mask, n, 48) and then divides mask by b for the next iteration.
Caveats
While the algorithm itself should be O(L), the actual output is going to have some worthless zeros at the start for most values of n that may have to be stripped. In addition, I’m not going to explain how to create a string in C, or how to implement this in other languages. You’re on your own there.
Also note that while the premise should be solid and I haven’t seen a situation where it fails, I disavow all responsibility for algorithmic failures and weaknesses.
EDIT: Daniel Bruce informed me that the function sprintf() would do the job just as well, only should also work for floating point numbers and is more flexible. I wish I had known about that before I had spent the time to write this algorithm.
Posted in Programming |