c++ - How can I refer to sub-elements in a particular variable? -
my problem follows: have 64 bit variable, of type uint64_t
(so know it's specified @ least 64 bits wide).
i want able refer different parts of it, example breaking down 2 uint32_t
s, 4 uint16_t
s or 8 uint8_t
s. there standards compliant way doesn't rely on undefined behavior?
my approach follows:
class buffer { uint64_t m_64bitbuffer; public: uint64_t & r64() { return m_64bitbuffer; } uint32_t & r32(r32::part part) { return *(reinterpret_cast<uint32_t*>(&m_64bitbuffer)+part); } uint16_t & r16(r16::part part) { return *(reinterpret_cast<uint16_t*>(&m_64bitbuffer)+part); } uint8_t & r8(r8::part part) { return *(reinterpret_cast<uint8_t*>(&m_64bitbuffer)+part); } };
where r32::part
, r16::part
, r8::part
enum
s define values between 0 , 1, 0 , 3 , 0 , 7 respectively.
i imagine should ok. there should no issues alignment, example. i'd know if i'm breaking rules, , if so, how properly.
type-punning through union allowed compilers, have following anonymous union member:
union { uint64_t val; struct { uint32_t as32[2]; }; struct { uint16_t as16[4]; }; struct { uint8_t as8[8]; }; } u;
access each part easy reading appropriate member.
Comments
Post a Comment