Hello all,
I'm trying to do an assignment, but I'm really struggling (in the middle of class someone yelled "THIS IS SO HARD" so I'm pretty sure I'm not the only one haha), and I would appreciate help. To start off, this is the first problem:
Write a getBits function which takes as input a starting bit number low (int), an ending bit number high (int) and an unsigned int source and extracts from source the bits in the range specified and returns them in the low order bits of an unsigned int. Bit numbering goes from 0 (least significant bit) to 31. If the values of low or high are invalid, the function should return 0. For example:
printf("%d\n", getBits(2, 5, 6));
should cause the value 1 to be displayed.
printf("%d\n", getBits(2, 3, 13));
should cause the value 3 to be displayed.
Hint: you can do this with two shifts.
The next few are pretty similar to this one, so I think if someone can point me in the right direction, I can figure out the rest.
So far I have :
That basically just covers all of the cases for invalid inputs. I've tried a few things with shifting, but I'm not getting anywhere and I think I'm just confusing myself more. We were never really taught about masks, but I read about them in our book, so I'm pretty sure that's what we're supposed to use, but I'm not really clear on how to use them. I feel like I'm supposed to take the source and shift over the high input and store it in a variable, do the same thing with the low, and then do something comparing the two variables but everything I have tried so far hasn't worked. Am I on the right track or totally off?Code:unsigned int getBits(int low, int high, unsigned int source) { if (low > high || low < 0 || high > 31) { return 0; } unsigned int input = source; int mask = ??? }
Thanks!