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*/
Bit manipulation is the act of algorithmically manipulating bits or other pieces of data shorter than a byte. C language is very efficient in manipulating bits.
The C++ language does not include a data type that allows us to represent a single bit. Instead, we have to work with groups of bits. The smallest group of bits the language allows use to work with is the unsigned char , which is a group of 8 bits.
printf("int has %ud bits\n", sizeof(int) * 8); sizeof() returns the size in bytes of an integer, and then you multiply that result by 8 (bits per byte in 99.999% of cases)to get the size in bits of your integer, and therefore the size of the masks you have to apply.
Why not create a bit structure like you have but then place it inside a union? I dropped the typedef so it uses C++ style definitions.
struct instruction
{
int op_code : 6;
int reg_dest : 5;
int reg_s1 : 5;
int offset :16;
};
union INST
{
instruction a;
uint32_t b;
};
You could store/load the 32-bit values using network functions:
INST i;
i.b = ntohl(value);
And now you can reference the bit fields without typecasting.
if (i.a.op_code == XXX)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With