0

I need to convert an unsigned long long to a string without using any stdlib or stdio functions.

Can anyone suggest a way to do this or provide an algorithm?

I attempted to use some bitwise math but my compiler tells me that the shift is too large. Thanks in advance!

sukhvir
  • 5,265
  • 6
  • 41
  • 43
Neil Locketz
  • 4,228
  • 1
  • 23
  • 34
  • 2
    Is there anything unusual about the architecture you're working on that would prevent you from using division and modulo by 10? –  Nov 08 '13 at 23:13
  • 3
    You could do it like this: `char const * to_string(unsigned long long n) { return "a long"; }` Produces a string when given an integer. – Kerrek SB Nov 08 '13 at 23:13
  • http://stackoverflow.com/questions/19865471/get-number-into-a-string-c-without-stdio – Drakosha Nov 08 '13 at 23:14
  • @Drakosha That post is about signed int. To get the full range of signed vs. unsigned, various subtle coding variations occur, though the overall algorithm is similar. – chux - Reinstate Monica Nov 08 '13 at 23:19
  • 2
    modulo 10, divide 10, repeat if needed. '0' + 2 = '2'. – Charlie Burns Nov 08 '13 at 23:22
  • the mod 10 thing would work, I'm not sure how to execute it so the most significant digit is the first char in the array – Neil Locketz Nov 08 '13 at 23:26
  • @KerrekSB - _Funny_, well you _were_ truthful. It does return a string when given a long long. – ryyker Nov 08 '13 at 23:38
  • @ryyker: And I was quite serious, too. Unless the OP can describe precisely why that solution doesn't suffice, there's no reason to do anything more complicated. And if he *can* describe why it doesn't suffice, then *that should be part of the question*. Either way, some thinking will have been done, which I count as a win. – Kerrek SB Nov 09 '13 at 00:09

1 Answers1

1

A recursive solution

static char *ullTostring_Helper(unsigned long long i, char *s) {
  if (i >= 10) {
    s = ullTostring_Helper(i/10, s);
  }
  *s++ = i%10 + '0' ;
  return s;
}

char *ullTostring( unsigned long long i, char *dest) {
  *ullTostring_Helper(i, dest) = '\0';
  return dest;
}

A non-recursive solution with no function calls

char *ullTostring2(unsigned long long i, char *dest) {
  char buf[(sizeof i)*3 + 3];
  char *p = &buf[sizeof(buf) - 1];
  *p = '\0';
  do {
    p--;
    *p = i%10 + '0';
    i /= 10;
  } while (i);
  char *dest2 = dest;
  do {
    *dest2++ = *p;
  } while (*p++);
  return dest;
}
chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256