繁体   English   中英

在 ANSI C 中使用 union 将四个 uint8_t 的数组转换为 uint32_t

[英]Using union to convert array of four uint8_t to uint32_t in ANSI C

我正在 XC8(Microchip 8 位微控制器的 C 编译器,可能基于 gcc)中处理一些代码。

我正在使用许多字节数组 -> 随便什么 -> 类似于此的字节数组转换:

inline int32_t GetInt32(uint8_t b3, uint8_t b2, uint8_t b1, uint8_t b0)
{
    int32_t b_31_24 = (((int32_t)b3) << 24);
    int32_t b_23_16 = (((int32_t)b2) << 16);
    int32_t b_15_08 = (((int32_t)b1) << 8);
    int32_t b_07_00 = b0;

    return b_31_24 + b_23_16 + b_15_08 + b_07_00;        
}

我可以像这样使用 union 吗?

typedef union {
    int32_t int32value;
    uint32_t uint32value;
    int16_t[2] int16words;
    uint16_t[2] uint16words;
    int8_t[4] int8bytes;
    uint8_t[4] uint8bytes;
} union32_t;

我想减少 CPU 和/或内存使用量。

让我们假设:

  • 此代码将与相同的编译器一起使用
  • 我知道字节序是什么,在我不知情的情况下它不会改变:)
  • 我知道不同的编译器在对齐方面可能有不同的行为(我测试了 Microchip XC8、XC32、一些 STM 编译器)。

我为什么要问这个?

我想确定,在将byte arrayint等时,数组是否没有“未定义行为”之类的问题。

工会双关语是 100% 罚款。 根本没有问题(字节序除外)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM