Connecting Tech Pros Worldwide Forums | Help | Site Map

print hex in n-bit format

John
Guest
 
Posts: n/a
#1: Sep 29 '06
printf("Hex = %#x\n", 28); will print out 0x1c

What if I want to print 0x001c for 16-bits?, or even 0x0000001c with
32-bits?

can i adjust the format in my case?

please advice. thanks!!


Michael Mair
Guest
 
Posts: n/a
#2: Sep 29 '06

re: print hex in n-bit format


John wrote:
Quote:
printf("Hex = %#x\n", 28); will print out 0x1c
>
What if I want to print 0x001c for 16-bits?, or even 0x0000001c with
32-bits?
>
can i adjust the format in my case?
#include <stdio.h>
#include <limits.h>
int main (void)
{
printf("Hex = %0#6x\n", 28);
#define NIBBLE_FMT(e) (sizeof (e) * CHAR_BIT + 3)/4+2, (e)
printf("Hex = %0#*x\n", NIBBLE_FMT(28));
return 0;
}

Cheers
Michael
--
E-Mail: Mine is an /at/ gmx /dot/ de address.
Hubble
Guest
 
Posts: n/a
#3: Sep 29 '06

re: print hex in n-bit format



John wrote:
Quote:
printf("Hex = %#x\n", 28); will print out 0x1c
>
What if I want to print 0x001c for 16-bits?, or even 0x0000001c with
32-bits?
>
can i adjust the format in my case?
>
please advice. thanks!!
use a "field width" to specify the length. A leading 0 before the width
will insert 0's instead of spaces, so

printf("%#06x",28)

prints 0x001c, whereas

printf("%#010x)

can be used for 32 bits.

Hubble.

Closed Thread