簡體   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