Thursday, March 14, 2013

How can I pad an int32 or int64 with leading zeros replacement of sprintf

#define hexchar(x) ((((x)&0x0F)>9)?((x)+'A'-10):((x)+'0'))
typedef signed long long Int64;

// special printf for numbers only
// see formatting information below
// Print the number "n" in the given "base"
// using exactly "numDigits"
// print +/- if signed flag "isSigned" is TRUE
// use the character specified in "padchar" to pad extra characters
//
// Examples:
// sprintfNum(pszBuffer, 6, 10, 6, TRUE, ' ', 1234); --> " +1234"
// sprintfNum(pszBuffer, 6, 10, 6, FALSE, '0', 1234); --> "001234"
// sprintfNum(pszBuffer, 6, 16, 6, FALSE, '.', 0x5AA5); --> "..5AA5"
void sprintfNum(char *pszBuffer, int size, char base, char numDigits, char isSigned, char padchar, Int64 n)
{
char *ptr = pszBuffer;

if (!pszBuffer)
{
return;
}

char *p, buf[32];
unsigned long long x;
unsigned char count;

// prepare negative number
if( isSigned && (n < 0) )
{
x = -n;
}
else
{
x = n;
}
// setup little string buffer
count = (numDigits-1)-(isSigned?1:0);
p = buf + sizeof (buf);
*--p = '\0';
// force calculation of first digit
// (to prevent zero from not printing at all!!!)
*--p = (char)hexchar(x%base);
x = x / base;
// calculate remaining digits
while(count--)
{
if(x != 0)
{
// calculate next digit
*--p = (char)hexchar(x%base);
x /= base;
}
else
{
// no more digits left, pad out to desired length
*--p = padchar;
}
}

// apply signed notation if requested
if( isSigned )
{
if(n < 0)
{
*--p = '-';
}
else if(n > 0)
{
*--p = '+';
}
else
{
*--p = ' ';
}
}

// print the string right-justified
count = numDigits;
while(count--)
{
*ptr++ = *p++;
}

return;
}

No comments: