Bit Manipulation Lab
7) Allow the user to input 8 integer values all between 0 and 15 inclusive. Store these 4 values into a single 32 bit integer named "packit" Allow the user to choose which of the 8 integers they wish to recover from "packit". An input of 1 will recover the first value input, a 2 the second, a 3 the third, etc. Use only bit manipulations to store and recover the values. Optionally you may also output the value in its binary format in addition to its base 10 value.
My teacher gives all his projects at the same time so we have not learned bit manipulation yet, I just wanted to get a head start on it if someone could point me in the right direction
Ok. Hopefully I got all the code stuff right. If not, hopefully the concept is clear anyway..
bitwise functions:
>> shift 1 bit. so 8 >> 1 is 4.
<< shift the other way, 4 << 1 is 8.
| or each bit of 2 integers. Not to be confused with ||, which ors the entire value of the integers together as Booleans (not zero = true).
& bit and (&& is Boolean as above)
^ xor
~ not (I think?)
there might be a nand in there somewhere. I forget.
so say you had a 32 bit unsigned int:
uint32_t x = 0x 12 34 56 78 //broken up hex value for the example. not code.
now say you wanted to put 11 decimal (0x0B) into it at the highest order byte .
one way to do that is to put 11 into another int and shift it:
uint32_t y = 11;
y << 24;
should produce
0B 00 00 00
now, you can clear the high bits of X:
x &= 0x00FFFFFF which retains what was in the lower 3 bytes and zeros out the high 4th byte. x is now 00 34 56 78
and finally you can OR them to assign (or just add, like a normal person)
x |= y; //x is now 0B 34 56 78
you probably want a full set of clear constants defined, 00 ff ff ff, ff 00 ff ff, ff ff ff 00, etc... its usually best to do a bunch of house keeping up front so your code is really clean after when doing this stuff.
By the way, this bit stuff is almost always silly. A lot of programmers get fired up and excited to get to use hex or binary, but its just shooting yourself in the foot, you do a lot of extra work more often than not.