Using Union for combining registers

Hello everyone,
I was wondering how I could use unions to combine registers elegantly. For example I have the 8 bit registers B and C & I have opcodes that work on each independent register such as add b, c, which is simple, but then I also have opcodes that work on both of them as if they're one like ld a, bc. I know I could go about that by just masking them together but I've seen it done with unions before & it made everything so much more simple.
Thanks in advance
bump
This can be done but:

1) It relies on behavior which is not formally defined by the language. IE: you risk it being broken in a future version of <insert compiler here>

2) It is subject to system endianness and is not portable.


Example:

1
2
3
4
5
6
7
8
9
10
union Reg
{
    uint16_t ab;
    struct
    {
        uint8_t a;
        uint8_t b;
    };
};


On most but not necessarily all compilers... and on little endian systems... this will result in 'a' occupying the low 8 bits of 'ab' and 'b' occupying the high 8 bits of 'ab'.

But again... not portable, relies on undefined behavior... etc, etc, etc. I don't recommend it.

EDIT:
If you want a portable way to do this that doesn't rely on nasty tricks that may break.... wrap this stuff in a class and use getters/setters:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Reg
{
public:
    inline uint16_t ab()            { return reg;                               }
    inline uint8_t  a()             { return static_cast<uint8_t>(reg & 0xFF);  }
    inline uint8_t  b()             { return static_cast<uint8_t>(reg >> 8);    }
    
    inline void     ab(uint16_t v)  { reg = v;                                  }
    inline void     a(uint8_t v)    { reg = (reg & 0xFF00) | v;                 }
    inline void     b(uint8_t v)    { reg = (reg & 0x00FF) | (v << 8);          }
    
private:
    uint16_t reg;
};
Last edited on
closed account (o1vk4iN6)
It relies on behavior which is not formally defined by the language. IE: you risk it being broken in a future version of <insert compiler here>

Isn't that more dependent on the OS and the ABI than the compiler ?
All of the above.
Topic archived. No new replies allowed.