okay, I haven't had to do much development work in c++, I spend most of my time in c#. I am trying to finish a course and my teacher gave an assignment on dealing with union and bitfield structure. The assignment is:

Write a C++ program that reads a 64-bit machine instruction and extracts the values for its components from certain bits, specified as follows:

Bits 0-4 code (the instruction code)
Bits 5-8 ladrm (left address mode)
Bits 9-12 radrm (right address mode)
Bits 13-19 si (short immediate)
Bits 20-25 lreg (left register)
Bits 26-31 rreg (right register)
Bits 32-63 li (long immediate)

You will be given a string of 16 hexadecimal digits, such as 08800080000004D2, which represents the numeric value of the 64 bits to be analyzed. The output for this input string should be:

Instruction: 08800080000004D2
rreg = 0
lreg = 2
si = 0
radrm = 0
ladrm = 1
code = 1
li = 1234

To get full credit for this program, you’ll need to use a union and a bit-field structure. Any C book and most C++ books talk about these language features. Use no bitwise operators. Your union object will overlay an unsigned int and a bit-field structure that matches the first 32 bits of the machine instruction. Read the first 8 hex digits into an unsigned int and assign it to your union. If you’re using an Intel machine, however, remember that it is a little-endian machine, which means you’ll have to reverse the order of the bit layout to extract the correct values. Then read the last 8 digits into an unsigned int for the long immediate value.


I am not really sure what he is asking. I know I am suppose to use a bit field structure which is:

struct INSTRUCTION
{
unsigned int code : 4;
unsigned int ladram : 4;
unsigned int radrm : 4;
unsigned int si : 7;
unsigned int lreg : 6;
unsigned int rreg : 6;
unsigned int li : 32;

};

but I am really not sure where to go. If I can get some better explanation of a bit field structure and a union and how they work I can figure out the rest but I have been searching and haven't really found how these work.

A union is just a structure in which all objects occupy the same space. For example

union 
{
   int a;
   char buf[20];
   float b;
   double c;
}

In the above, the union has only one real object but it can be used by any of the names provided, such as a, b, c or buf. The size of the union is always the size of its largest object, 20 in this case. So what you need to do is make a union between the INSTRUCTION strucure and an unsigned long integer.

uinion
{
    INSTRUCTION ins;
    unsigned long ln;
};

Since sizeof(INSTRUCTION) is the same as sizeof(ln), whatever you set ln to be will be reflected in the ins structure. So if you set ln = 0x8800080000004D2, then you can get the individual bits by using the ins structure.

Comments
helpful in answering questions.
This question has already been answered. Start a new discussion instead.