Friday, June 15, 2007

十六進位轉換(內建)

我把那個function貼過來
到今天我才知道,當你叫一個printf時候
他真的去call很多function的說 好複雜呀
我有把轉換的地方標出來了

static char *number(char *str, long num, int base, int size, int precision, int type)
{
char c, sign, tmp[66];
char *dig = digits;
int i;

if (type & LARGE) dig = upper_digits;
if (type & LEFT) type &= ~ZEROPAD;
if (base < 2 || base > 36) return 0;

c = (type & ZEROPAD) ? '0' : ' ';
sign = 0;
if (type & SIGN)
{
if (num < 0)
{
sign = '-';
num = -num;
size--;
}
else if (type & PLUS)
{
sign = '+';
size--;
}
else if (type & SPACE)
{
sign = ' ';
size--;
}
}

if (type & SPECIAL)
{
if (base == 16)
size -= 2;
else if (base == 8)
size--;
}

i = 0;

if (num == 0)
tmp[i++] = '0';
else
{
while (num != 0)
{
tmp[i++] = dig[((unsigned long) num) % (unsigned) base];
num = ((unsigned long) num) / (unsigned) base;
}
}

if (i > precision) precision = i;
size -= precision;
if (!(type & (ZEROPAD | LEFT))) while (size-- > 0) *str++ = ' ';
if (sign) *str++ = sign;

if (type & SPECIAL)
{
if (base == 8)
*str++ = '0';
else if (base == 16)
{
*str++ = '0';
*str++ = digits[33];
}
}

if (!(type & LEFT)) while (size-- > 0) *str++ = c;
while (i < precision--) *str++ = '0';
while (i-- > 0) *str++ = tmp[i];
while (size-- > 0) *str++ = ' ';

return str;
}

No comments: