468,512 Members | 1,535 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 468,512 developers. It's quick & easy.

print hex in n-bit format

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!!

Sep 29 '06 #1
2 13244
John wrote:
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.
Sep 29 '06 #2

John wrote:
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.

Sep 29 '06 #3

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

12 posts views Thread by Michael Foord | last post: by
14 posts views Thread by Marcin Ciura | last post: by
reply views Thread by bearophileHUGS | last post: by
1 post views Thread by Steff | last post: by
69 posts views Thread by Edward K Ream | last post: by
7 posts views Thread by samslists | last post: by
reply views Thread by NPC403 | last post: by
1 post views Thread by fmendoza | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.