471,850 Members | 900 Online
Bytes | Software Development & Data Engineering Community
Post +

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 471,850 software developers and data experts.

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 13818
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 YellowAndGreen | last post: by

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.