Bit Masking Homework

For this assignment you will write some C code to use bit shift operations and the bitwise “and” operation on an integer.

See the home page for the example bitwise code from class.

Bit Masks

Bit masking is the technique of using bitwise operations to retrieve or manipulate the bits of a stored value.

For example, to get the 4 least significant bits of a number, you can perform a bitwise “and” (the & operator) with 0xF, which is 1111. Assuming the original number is an 8-bit number, that looks like this:

  01101110
& 00001111
  --------
  00001110

In this case, 0xF is called the mask.

As we saw in class, you can use the left and right shift operators (<< and >>) as well as the other bitwise operators (or is |, xor is ^, and not is ~) to get the values of certain bits, toggle bits on and off, etc.

Provided Code

You are provided with a file named bit_masking.c. Recall that you compile a C program on the command line like so:

gcc bit_masking.c -o bit_masking

When you run the executable, you will be asked to enter a non-negative integer, and it will print the decimal and hex representations:

$ ./bit_masking
Enter a non-negative integer: 1234
decimal: 1234
hex:     0x4D2

Your Changes

You are to add code to this file so that it prints out the 32-bit binary representation of the number, and the hex representations of each of the 4 bytes in the stored representation, from most to least significant. So after your changes, the output should look like this:

$ ./bit_masking
Enter a non-negative integer: 1234
decimal: 1234
hex:     0x4D2
binary:  00000000000000000000010011010010
individual bytes, from most to least significant:
0x00
0x00
0x04
0xD2

C does not provide a way to print out the binary representation of a number. You will have to print the binary yourself, 1 bit at a time. To get the Nth bit (where the least significant bit is the 0th bit) you need to shift the number to the right N places, which places the bit you are interested in at the rightmost position, and then use 1 as a mask to isolate the least significant bit. Use a loop to print out each bit this way.

To get one of the bytes from the number you need a mask that is 8 1’s (0xFF). You can then shift the number so that the byte you want is in the least significant 8 bits of the number, and then apply the mask.

git-keeper will be picky about the output being 2 hex digits for each byte. The printf() conversion specification for 2-digit hex is %02X.

Grading

Your grade will be based on the following: