0

i have a 32 bit instruction that i wish to split into four bytes. Let say the instruction looks like this:

yyyyyzzzzzzxxxxxx?????????

The instruction is a word that consists of four unsigned ints. y represents the operation code, and ??? are for the unused space. I am working on a big-endian machine.

What I would like to happen is to move the values from z + w to a.

I have never worked in C before but I have tried to do it like this.

Here is how I read the word, just so I ca print out each byte:

unsigned int a, b, c, o;
w = instruction << 24;
z = instruction << 16;
x = instruction << 8;
y = instruction;

Here I print unsigned values, just to check what the result are.

printf("%u\n", w);
printf("%u\n", z);
printf("%u\n", x);
printf("%u\n", y);
printf("\n");

regs[x] = instruction + instruction << 8;

if I print out the values of regs[x] after this, then I can see that I has a value now, but is this the correct way of doing it? When I do like this, do I set the register = z + w?

EDIT Mabye i should get the bits like this?

            y = (inst >> 24) & 077;
            x = (inst >> 16) & 0xffff;
            z = (inst >> 8) & 0xffff;
            w = (inst) & 0xffff;

and then do like this:

regs[y] = z + w;
user123
  • 13
  • 3
  • Please note that a "byte" is generally considered 8 bits, so splitting 32 bits into four bytes and still getting three unused bits is kind of hard. Also when illustrating a word like that, each letter should typically represent one bit. But you only show 23 letters (including the `?`s at the end), making this hard to interpret. – unwind Apr 11 '17 at 08:12
  • @unwind sorry, yes i should have written it like this yyyyyzzzzzzxxxxxx????????? maybe i have misunderstood what i had to do, i have made an edit to the question – user123 Apr 11 '17 at 10:01

1 Answers1

0

If you like to use only bit positions and counts you can build a bit mask of i.e. 9 bits with setting the next bit and decrement (1<<10)-1. So your values are

#define MASK(n) ((1<<(n+1))-1)

unsigned int w = instruction & MASK(9);
unsigned int x = (instruction >> 9) & MASK(6);
unsigned int z = (instruction >> 15) & MASK(6);
unsigned int y = (instruction >> 21) & MASK(5);

all values are down shifted. So if you like to combine z and w you will have to

unsigned int zw = z<<9 | w; 

because w contains 9 bits, or

unsigned int wz = w<<6 | z; 

because z contains 6 bits.

Holger
  • 899
  • 2
  • 7
  • 12
  • this looks like the way i wanted to do it, can you explain what the MASK definition does? do it extend with zeros? if that question make sense – user123 Apr 11 '17 at 11:26
  • MASK(9) builds a 32-bit value of `0b00000000000000000000000111111111`. If you use this mask in an `&` operation, you get the value of all bits which in mask are set to 1. – Holger Apr 11 '17 at 11:30
  • that makes sense! so, if i wanted to extend to 16 bit i could put MASK(6), thanks for the help – user123 Apr 11 '17 at 11:40