I Have found a way to make a n-bit integer and do arithmetic on the integers, But I don't know how to print those integers, My method to make a n-bit integer is just to make an array of, lets say char
's, and make the array (size of array elements) / n elements long. Does anyone know how to print these?
You can't use standard library functions to convert to string or print in base != 2, 4, 8, 16 (generally 2^n).
If you want to print using those bases you can easily write your own function (example one assuming little endian)
void printInteger(const void *buff, size_t size, int base)
{
const char digits[] = "0123456789ABCDEF";
const unsigned char *uc = buff + size - 1;
unsigned nbits;
unsigned mask;
switch(base)
{
case 2:
nbits = 1;
break;
case 4:
nbits = 2;
break;
case 8:
nbits = 3;
break;
case 16:
nbits = 4;
break;
default:
return;
}
mask = (1U << nbits) - 1;
while(size--)
{
for(int nb = CHAR_BIT / nbits - 1; nb >= 0; nb--)
{
printf("%c", digits[(*uc >> (nb * nbits)) & mask]);
}
uc--;
}
}
int main(void)
{
unsigned test = 0x12345678;
printInteger(&test, sizeof(test), 16);
printf("\n");
printInteger(&test, sizeof(test), 8);
printf("\n");
printInteger(&test, sizeof(test), 4);
printf("\n");
printInteger(&test, sizeof(test), 2);
printf("\n");
}