如何附加到相邻的十六进制值,然后显示

How to attach to hex values next to each other and then display

本文关键字:然后 显示 十六进制 何附加      更新时间:2023-10-16

假设我有以下内容。

int main(){
    int x = 0x02;
    int y = 0x72;
    //Figure out how to put 0x02 and 0x72 together to make 0x272.
}

正如评论所说,我想弄清楚如何将十六进制值组合在一起。这不是简单的数字相加。

上面的代码是一个更大项目的一部分,我想知道如何解决这个问题。

是的,这是一个简单加法的问题,因为乘法是很多简单加法。:-)

我建议使用乘法(并使用无符号整数):

unsigned int x = 0x02;
unsigned int y = 0x72;
unsigned int combined = (x * 256) + y;
// Or the equivalent
unsigned int result = (x * 0x100) + y;

这个解决方案是独立于平台的,不依赖于Endinaness。

类似:

int main(){
  int x = 0x02;
  int y = 0x72;
  int z = x << 8 | y;
  printf("0x%xn", z);
  z = y << 8 | x;
  printf("0x%xn", z);
}

输出:

0x272
0x7202

相关文章: