将uint8_t [4]转换为unsigned long

时间:2018-11-10 19:51:27

标签: c bit-manipulation

我试图将{{1}的uint8_t[4](或仅4个uint8_t)转换为单个无符号长(特别是GUIDhttps://msdn.microsoft.com/en-us/14288352-43c3-4e4d-a3f1-e924a8261d2b)结构的Data1部分}}

我的天真的做法是:

Rpc.h

但是,正如我本可以告诉自己的那样,最后一行覆盖了中间一行,导致newUUID.Data1为UUID newUUID; newUUID.Data1 = 0x0a << 24; newUUID.Data1 = 0x04 << 16; ... 而不是00040000

如何设置第9-16位最高有效位,同时保留1-8位最高有效位?

2 个答案:

答案 0 :(得分:4)

您可以使用|=运算符来设置这些新的,不重叠的位范围:

UUID newUUID;
newUUID.Data1 = 0x0a << 24;
newUUID.Data1 |= 0x04 << 16;

答案 1 :(得分:3)

这是工作中非常常见的事情,我为此定义了一些宏:

results: (
    1,
    2,
    3,
    4
)

您可以这样做:

#include <stdint.h>

#define B4TODW_LE(c0, c1, c2, c3) (uint32_t) ((uint32_t) (uint8_t) (c0) | ((uint32_t) (uint8_t) (c1) << 8) | ((uint32_t) (uint8_t) (c2) << 16) | ((uint32_t) (uint8_t) (c3) << 24))
#define B4TODW_BE(c0, c1, c2, c3) (uint32_t) ((uint32_t) (uint8_t) (c3) | ((uint32_t) (uint8_t) (c2) << 8) | ((uint32_t) (uint8_t) (c1) << 16) | ((uint32_t) (uint8_t) (c0) << 24))