Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Easiest way to print 64 bit hex data splitted by 16 bits

Tags:

c

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?

like image 308
Patrick Avatar asked Dec 18 '22 02:12

Patrick


1 Answers

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) );
}
like image 160
Lundin Avatar answered Dec 29 '22 00:12

Lundin