C语言 从数组中提取字符作为 UINT32



所以我有一个缓冲区,里面装满了我知道至少应该有 16 个字节长的字节。我不在乎字节 0 - 11。我知道从 12 到 15 的 4 个字节代表一个 32 位数字。

我怎样才能提取这些字节并将它们表示为 32 位数字。

您可以将每个字节转换为 8 位无符号数字,并且可以使用位运算将这些数字组合为一个 32 位数字:

uint32_t result = 0;
for (int i = 12; i < 16; i++) {
    result <<= 8;
    result |= (uint8_t)bytes[i];
}

我对unions{}有执着,我忍不住。这可能会有所帮助:

#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <arpa/inet.h>
uint32_t
convert_int(char bytes[4])
{
        union {uint32_t n; char bytes[4];} box;
        memcpy(&box.bytes[0], bytes, sizeof(*bytes));
        return ntohl(box.n);
}
int
main(void)
{
        uint32_t number;
        number = convert_int("x0Ax00x00x00");
        printf("%dn", number);
        return 0;
}

convert_int() 接受 4 个字节的网络字节顺序(大端序)(最高有效字节优先),并将其转换为 32 位整数;主机字节顺序(大端或小字节序)。由于您可以控制缓冲区,因此可以根据需要放置参数。

最新更新