c - 如何在C中连接数组中的十六进制数据

标签 c arrays hex concatenation

我的数据字段如下 DATA = 0x02 0x01 0x02 0x03 0x04 0x05 0x06 0x07 现在我想按如下方式连接此数据 DATA = 0x01020304050607。我怎样才能使用 C 程序来做到这一点。我在 C 中找到了一个程序,用于连接数组中的数据,程序如下:

#include<stdio.h>

int main(void)
{
    int num[3]={1, 2, 3}, n1, n2, new_num;
    n1 = num[0] * 100;
    n2 = num[1] * 10;
    new_num = n1 + n2 + num[2];
    printf("%d \n", new_num);
    return 0;
}

对于数组中的十六进制数据,如何操作上面的程序来拼接十六进制数据?

最佳答案

您需要一个 64 位变量 num 作为结果,而不是 10 作为您需要 16 的因素,而不是 100 作为因素,您需要 256

但是如果您的数据以字节数组的形式提供,那么您可以简单地插入完整的字节,即重复移动 8 位(即 256 倍):

int main(void)
{
    uint8_t data[8] = { 0x02, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07 };
    unsigned long long num = 0;
    for (int i=0; i<8; i++) {
        num <<=8;  // shift by a complete byte, equal to num *= 256
        num |= data[i];  // write the respective byte
    }
    printf("num is %016llx\n",num);
    return 0;
}

输出:

num is 0201020304050607

关于c - 如何在C中连接数组中的十六进制数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51012515/

相关文章:

c++ - glTexImage2d 和空数据

c# - 使用 Console.ReadLine() C# 读取地址

c - 为什么我的程序永远重复而不是给出最大整数值?

C 未正确存储数组中的第一个条目

c - 函数只返回字符串的字母

c++ - 如何将数组的内容写入文本文件?

java - 我无法理解 Merge Sorted Array 的示例测试用例?

c - "initialization makes integer from pointer without a cast"数组初始化中逐渐减弱

c - 在 C 中将字符数组打印为十六进制

python - 使用采样数据时,CRC32 函数如何工作?