简体   繁体   中英

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

I'm working on some code in XC8 (C compiler for Microchip 8 bit microcontrollers, probably based on gcc).

I'm using many byte array -> whatever and whatever -> byte array conversions similar to this:

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;        
}

Can I just use union like this?

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;

I want to reduce CPU and/or memory usage.

Lets assume:

  • this code will be used with same compiler
  • I know what endiannes is and it won't change without my knowledge :)
  • I know that diffrent compilers may have diffrent behavior regarding alignment (I have tested Microchip XC8, XC32, some STM compiler).

Why I'm asking about this?

I want to make sure, if there are no issues with arrays like "undefined behavior" when casting byte array to int etc.

union punning is 100% fine. there are no issues (except endianes) at all.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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