2013-08-29

C: conversion from int to string in a given base

char* baseconv(unsigned long long num, int base)
{
 char* retbuf = (char*)calloc(65, sizeof(char));
 char *p;

 if(base < 2 || base > 16)
  return NULL;

 p = &retbuf[64];
 *p = '';

 do {
  *--p = "0123456789abcdef"[num % base];
  num /= base;
 } while(num != 0);

 return p;
}

The base can be any integer between 2 and 16. If you expand the string on line 13, you can increment the limit in line 6.

Why is retbuf 65 char long? The largest parameter value we can get is 264-1. In hexadecimal is 0xFFFFFFFFFFFFFFFF, 16 pieces of "0xF", plus the '\0' at the end. Without the "0x", of course, which we do not prepend.
But in binary, 264-1 = 11111111111111111111111111111111111111111111111111111111111111112, 64 pieces of "1", plus the final '\0'.

No comments :

Post a Comment