开发者

simulate ulltoa() with a radix/base of 36

I need to convert an unsigned 64-bit integer into a string. That is in Base 36, or characters 0-Z. ulltoa does not exist in the Linux manpages. But sprintf DOES. How do I use sprintf to achieve t开发者_开发知识库he desired result? i.e. what formatting % stuff?

Or if snprintf does not work, then how do I do this?


You can always just write your own conversion function. The following idea is stolen from heavily inspired by this fine answer:

char * int2base36(unsigned int n, char * buf, size_t buflen)
{
  static const char digits[] = "0123456789ABCDEFGHI...";

  if (buflen < 1) return NULL; // buffer too small!

  char * b = buf + buflen;
  *--b = 0;

  do {
    if (b == buf) return NULL; // buffer too small!

    *--b = digits[n % 36];
    n /= 36;
  } while(n);

  return b;
}

This will return a pointer to a null-terminated string containing the base36-representation of n, placed in a buffer that you provide. Usage:

char buf[100];
std::cout << int2base36(37, buf, 100);

If you want and you're single-threaded, you can also make the char buffer static -- I guess you can figure out a suitable maximal length:

char * int2base36_not_threadsafe(unsigned int n)
{
  static char buf[128];
  static const size_t buflen = 128;

  // rest as above
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜