Question: The code is to be written in C++. I amn supposed to run it in linux machine. Question: Using shifting and masks instead of unions

The code is to be written in C++. I amn supposed to run it in linux machine.

Question: Using shifting and masks instead of unions find a way to pack four unsigned chars into an unsigned int and a way to later extract the four unsigned chars. You can use the union technique and the writeBitsInInt() function to test your code.

I have attached a code which uses Union to do the same job for reference or help.

The type char is itself a type of integer, but with only 8 bits. We could pack four unsigned char into an unsigned int. One method to achieve this is to use a union. The types in a union occupy the same space in memory. Consider the following example: >$ cat packUIntUnion.cpp #include #include "writeBitsInInt.H" union PackUInt { unsigned char u8[4]; unsigned u32; }; int main() { PackUInt i; i.u32 = 0; i.u8[0] = 1; std::cout << writeBitsInInt(i.u32) << std::endl; i.u8[3] = 2; std::cout << writeBitsInInt(i.u32) << std::endl; i.u8[2] = 255; std::cout << writeBitsInInt(i.u32) << std::endl; } >$ g++ -ansi -pedantic -Wall packUIntUnion.cpp >$ ./a.out 00000000000000000000000000000001 00000010000000000000000000000001 00000010111111110000000000000001

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!