I want to print 64 bits hex data in following format:
0x1111_2222_3333_4444
I can think of following:
#define FIRST_MASK 0xFFFF000000000000
#define SECOND_MASK 0x0000FFFF00000000
#define THIRD_MASK 0x00000000FFFF0000
#define FOURTH_MASK 0x000000000000FFFF
val = 0x1111222233334444
printf("0x%04x_%04x_%04x_%04x\n", \
(unsigned int)((val & FIRST_MASK) >> 48),
(unsigned int)((val & SECOND_MASK) >> 32),
(unsigned int)((val & THIRD_MASK) >> 16),
(unsigned int)(val & FOURTH_MASK)
);
Is there a simple (or maybe more clean) way to achieve this?
Bit shifts are always the best method, because they are both fast and platform-independent. However, your code is needlessly complex: you can mask after shifting instead of before.
#include <stdint.h>
#include <stdio.h>
int main (void)
{
uint64_t val = 0x1111222233334444;
printf("0x%04x_%04x_%04x_%04x\n",
(unsigned int)(val>>48 & 0xFFFF),
(unsigned int)(val>>32 & 0xFFFF),
(unsigned int)(val>>16 & 0xFFFF),
(unsigned int)(val>> 0 & 0xFFFF) );
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With