Suppose we have a binary file, that contains 32 bit numbers. Each 32bit number represents an instruction. My question: is it possible to cut this bits into chunks of 6+5+5+16 directly. Something like:
typedef struct _instruction
{
int op_code : 6;
int reg_dest : 5;
int reg_s1 : 5;
int offset : 16;
} INST, *PINST;
int read_32_bits = read_next_instr();
INST i = (INST)read_32_bit; /* this would cut the bits into chunks*/
Here is an answer that will work, be portable, not invoke undefined behavior on any compiler, and be optimized fairly effectively:
This lets you access all of the bitfields with a very convenient notation. I think it’s also a POD, which lets you use it in a few interesting ways. And a good compiler will do a fairly decent job of optimizing the bit munging operations, especially if you have several calls to the convenience functions in a row.
It’s almost as nice as having an overlay bit field. It’s just a bit more work to define in the first place.
Also, I changed the type to
unsigned intbecause if you’re fiddling around with the bits, you really want a simply represented number without a sign bit or anything funky like that. Ideally you’d be including the<cstdint>header and using::std::uint32_tor something in the typedef at the top.