Search code examples
ccharhexdata-conversion

Convert long to 6 letter hex string


I have a long value and I would like to convert it into 6 digit hex string.

My Try:

long ID = some value;

char * hex = (char *) calloc(n, sizeof(char)); // dynamic memory required.

int c = sprintf(hex, n+1, "%x", ID);

assert(c == ID);

1) how would I find the value of 'n' to give to calloc?

2) how do I make the string only 6 hex characters?

Thanks.


Solution

  • Number of hex digits can be computed like this:

    int numberOfHexDigits(long ID)
    {
        int n=0;
        if (ID==0) {
            return 1;
        }
        while (ID!=0) 
        {
            ID >>= 4;
            n++;
        }
        return n;
    }
    

    Using calloc (or malloc) to allocate memory for just 7 bytes is wasteful. I assume you have a reason to do that. You are better off just doing this:

    const int nDigits = 6;
    char hex[nDigits+1];
    snprintf(hex, sizeof(hex), "%lx", ID);
    

    If you really want to allocate memory on the heap:

    int bufSize = numberOfHexDigits(ID)+1;
    char *hex = (char *) malloc(bufSize);
    snprintf(hex, bufSize, "%lx", ID);