以 C++ 为单位递增 16 字节字符数组

Increment 16 byte char array in C++

本文关键字:字节 字符 数组 C++ 为单位      更新时间:2023-10-16

我有一个数组

char msgID[16];

如何将其递增 1?我将高低 8 字节读入 2 个不同的uint64_t整数

uint64_t high, low;
memcpy(&low,  msgID, sizeof(uint64_t));
memcpy(&high, msgID + sizeof(uint64_t) , sizeof(uint64_t));

如果我这样做

low += 1;

如何解释溢出?

感谢您提供的任何帮助。

实际上,这很简单:

if(++low == 0)
    ++high;

msgID[15]和尖叫开始。如果它通过 255,它回到零,在前一个字节

for (int c = 15; c >= 0; c--)
    if (++msgID[c] != 0) 
            break;

根据建议的评论,进行字节序测试并相应地增加

int endian_test = 1;
unsigned char buf[4];
memcpy(buf, &endian_test, 4);
//buf will be "1000" for little-endian, and "0001" for big-endian
int is_little_endian = buf[0];
if (is_little_endian)
{
    for (int c = 0; c < 16; c++)
        if (++msgID[c] != 0)
            break;
}
else
{
    for (int c = 15; c >= 0; c--)
        if (++msgID[c] != 0)
            break;
}