DISQUS

CodingExperiments.Com: Integer->String conversion in C/C++

  • DGentry · 1 year ago
    I take it the stdio functions (sprintf/snprintf/etc) were not acceptable? Certainly sprintf is a considerably more heavyweight function than the loop you've defined.
  • i80and · 1 year ago
    Honestly? I wasn't aware of sprintf/snprintf when I wrote this. Quite the embarrassing oversight on my part. But ah well; you're right, it probably did speed up the loop I used it in a bit (although I'm not sure if the net difference would be significant). Plus I got a lot of fun out of designing this algorithm.
  • Kenneth Finnegan · 1 year ago
    Instead of 48, you could also hard code it as '0' (zero in single quotes), which will evaluate to 48 when compiled, but will be portable if compiled in some other character set, which is good in C.

    Would you mind if I added this to my website of C tricks with citation? http://ctips.pbwiki.com/

    As for the leading zeros, I've used a recursive function where it'll keep calling itself with n/10 until n==0, then add each digit to the next char in the array, index of which is returned back down the call stack. But by then, sprintf would probably be just as good, but you get the idea...
  • i80and · 1 year ago
    Yeah, setting the offset to '0' is probably a better idea than 48. Thanks for the tip.

    Sure, go ahead and add it. I'm not sure where it would be more useful than sprintf/snprintf, though. Cool site, incidentally.

    Interesting idea for recursion. I'd have have to play with that to fully get it, but I think I get the general idea.
  • mortonfox · 1 year ago
    itoa() does the same thing and in multiple bases too, although it is not a part of ANSI C.
  • i80and · 1 year ago
    I had heard of itoa(), but I wanted something fully portable; it didn't really matter in the grand scheme of things as the program was for my own personal use, but I smelled a fun programming problem coming a mile away.

    But thanks anyway.