Summary: In this laboratory, you will experiment with bit fields and bitwise operators in C.
Prerequisites: I/O, functions, and structs in C.
Contents:
a. Consider the following type definition. If we declare a variable of type packedtime_t in a C program, how many bytes do you expect that variable to consist of?
typedef struct {
unsigned int hours: 5;
unsigned int minutes: 6;
unsigned int seconds: 6;
} packedtime_t;
Write a short C program that calls the macro sizeof(packedtime_t) to confirm or refute your expectation. Does the result make sense to you?
You may also want to call sizeof(unsigned int) if you are unsure how much space an int usually requires.
b. Write a short C program that prompts the user for the hours, minutes, and seconds of the current time. Load these values into a packedtime_t variable, and then print the result in the format "hh:mm:ss". Print leading zeros if needed to ensure that the output contains two decimal digits in each position.
Suppose you are working on a simple ASCII text editor that inserts control characters into the text to indicate particular formatting. For example, you might have defined one character that is inserted at the start and end of a segment of bolded text, another character that is inserted before and after a segment of italicized text, and so on. Suppose also that you have defined all the control characters such that their highest-order bit is set to 1. (This is sufficient to distinguish them from the rest of the text since all ASCII characters are in the range [0,127], so their highest-order bits are all 0.)
Next, suppose this file has been produced by your text editor. If you take a look at it (say with the bash command less), you will see that it has some of your control characters embedded in it. Your task for this exercise is to write a program that reads the file (via input re-direction) and then writes a new file (via output re-direction) that has the special characters stripped out of it.
a. Write a program that prompts the user to enter an integer, and then prints out the binary representation of that integer. To make the output easier to read, your program should print the 32 bits in eight nibbles (i.e., groups of 4 bits each) with a space between each nibble. When thinking about how to approach the problem, consider using a mask that will help you determine the value in the highest-order bit (bit 31). You could then modify the mask so that it helps determine the value in bit 30. And so on.
Hint: If you use the right-shift operator to modify the mask, you should declare the mask as an unsigned int. If the right-shift operator is applied to a signed integer that is negative (i.e., its leftmost bit is 1), then during the right-shift operation the new leftmost bit will be filled with a 1, not a zero.