Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cutting bits in C++

Tags:

c++

c

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*/
like image 670
Andro Avatar asked Dec 02 '11 22:12

Andro


People also ask

Can C manipulate bits?

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.

How do you represent a bit in C++?

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.

How do I extract a bit from an integer?

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.


1 Answers

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)
like image 143
Jamie Royer Avatar answered Sep 23 '22 04:09

Jamie Royer