#Merging two 8 bit unsigned integers into a single 16 bit unsigned integer

7 messages · Page 1 of 1 (latest)

green cradle
#

What's the recommended way of merging two 8 bit unsigned integers into a single 16 bit unsigned integer?

typedef volatile union
{
    uint16_t TCNT;
    struct
    {
        uint8_t TCNTnL;
        uint8_t TCNTnH;
    };
} TCNT_t;

or

typedef volatile union
{
    uint16_t TCNT;
    struct
    {
        uint16_t TCNTnL:8;
        uint16_t TCNTnH:8;
    };
} TCNT_t;

?
I'm asking, because I've heard it's not recommended to do implicit casting in unions...

  • it's in an 8bit environment!
dreamy acornBOT
#

When your question is answered use !solved to mark the question as resolved.

Remember to ask specific questions, provide necessary details, and reduce your question to its simplest form. For tips on how to ask a good question run !howto ask.

pallid knot
#

u16 a = ((u16)t.h << 8) | t.l;

#

bottom union is probably wrong due to potential padding.

#

top one is ok; if you're really paranoid, add #pragma pack(1) to it

green cradle
#

!solved