4 ms·
I had to lookup what itoa is not being a C programmer. Which got me interested - how would you implement this? My inital thought is to do something like (in p
by fendale 16y ago
I had to lookup what itoa is not being a C programmer. Which got me interested - how would you implement this?
My inital thought is to do something like (in pseudo code):
str = '';
while (i > 0 ) {
# least significant digit
r = i % 10;
# throw away the least significant digit
i = i / 10;
case
when r = 0 then
str = '0' << str
when r == 1 then
str = '1' << str
... etc
end
}
return str;
Would I pass with that? Is there a better way?
- varjag 16y agoWell, itoa() stands for "integer to ASCII". You can use the property of sequential numbers (starting at 0x30 in ASCII table) to avoid the case statement.
- fendale 16y agoGood point, I actually thought of doing that and then dismissed it. Maybe the best perfoming way would be to use the remainder as the index to an array (suggested in another comment)?
- varjag 16y agoIt's C we talking about, just add the remainder to 0x30 and you get your character.
- Someone 16y ago[pedantic]: you should use '0', not 0x30. 1. The standard library C function atoi may be named 'ASCII to integer', but it should convert a numerical string in the platform's encoding to integer. For symmetry, itoa should convert an integer to a platform encoded numeric string, not to an ASCII numerical string. 2. Not all computers use ASCII for C strings. Because of that, '0' need not equal 0x30. For example, in EBCDIC, one has '0' == 0xF0. Utterly pedantic: IIRC, the C standard guarantees that '0' through '9' are contiguous and in order. If you know better, or aren't sure, use "0123456789"[i] to convert a 0...9 value to the corresponding char.
- varjag 16y agoI used 0x30 for didactic purposes, so that a person less familiar with C would understand what exactly is happening.
- deleted 16y ago[deleted]