打印64位十六进制数据的最简单方法是16位。

时间:2022-03-14 03:12:12

I want to print 64 bits hex data in following format:

我想打印64位十六进制数据如下格式:

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?

有没有一种简单(或者更干净)的方法来实现这个目标?

1 个解决方案

#1


11  

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) );
}

#1


11  

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) );
}