printf() formatting for hex uint32_t without missing zeros. (in c89)
printf() formatting for hex uint32_t without missing zeros. (in c89)
Wanted to print uint32 hex.
Tried "PRIx32", looked bad to me:
967407c0 23 4481d55f ffffff52 de3cd140
2fc aa7363cf fffff40d 563270c0 2b86
So... tried this. Dirty but worked:
/*******************************************************************************
Print a digit in hex.
*******************************************************************************/
void mpal_digit_t_print_hex(
mpal_digit_t * input)
{
uint8_t p_1, p_2, p_3, p_4, p_5, p_6, p_7, p_8;
p_1 = (uint8_t)(((*input) << 0) >> 28);
p_2 = (uint8_t)(((*input) << 4) >> 28);
p_3 = (uint8_t)(((*input) << 8) >> 28);
p_4 = (uint8_t)(((*input) << 12) >> 28);
p_5 = (uint8_t)(((*input) << 16) >> 28);
p_6 = (uint8_t)(((*input) << 20) >> 28);
p_7 = (uint8_t)(((*input) << 24) >> 28);
p_8 = (uint8_t)(((*input) << 28) >> 28);
printf(" %" PRIx8 "%" PRIx8 "%" PRIx8 "%" PRIx8 "%" PRIx8 "%" PRIx8 "%"
PRIx8 "%" PRIx8 "", p_1, p_2, p_3, p_4, p_5, p_6, p_7, p_8);
return;
}
Output:
61dd90ef ff6df47e a0a9abc0 011d7394 2311761f
f4402427 5c44ca40 0f86aba7 6aa5194f ecb9ed1e
Is there an elegant way to do this in c?
1 Answer
1
Those "symbolic" printf specifiers like PRIx32 are designed to be used with extra flags, if you need them. So you can do something like this:
PRIx32
printf("%08" PRIx32, hexval);
After string concatenation, this will typically turn into either %08x or %08lx. 8 specifies you want (at least) 8 digits, and 0 specifies 0-padding.
%08x
%08lx
8
0
@chqrlie I suppose, but you've got an extra
x.– Steve Summit
Jun 30 at 10:09
x
Yes of course! commenting with the android app is a pain. The alternate format string is
printf("%.8" PRIx32, hexval);. This format is useful when you need both 0 filling and a larger minimum width.– chqrlie
Jun 30 at 15:47
printf("%.8" PRIx32, hexval);
0
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
Alternately, one can use "% .8x" PRIx32
– chqrlie
Jun 30 at 10:02