11. Quiz, Structs

SoftSys Lecture Notes, Monday 3/15/21 #

Bit Manipulation #

The following exercise is taken from last week’s class.

Exercise #

For each problem, you need to implement a function in C that follows the given signature. In each problem, there are a few restrictions: you are limited to using certain operators, and you can only use a certain number of operators total.

You cannot use other operators, function calls, conditionals (if/else), or loops (for/while). You can define and use integers, but they can only be a single byte (between 0 and 255, inclusive).

Bitwise XOR #

Write a bitwise XOR function with this signature:

int bit_xor(int x, int y);

This function computes x ^ y, that is, the XOR of each of the respective bits of x and y.

You can use up to 14 of these operators:

& ~

Our attempt (MF, GA, HS, CC)

~(~(~(x & y) & x) & ~(~(x & y) & y))

Bitwise Inequality #

Write a bitwise inequality function with this signature:

int bit_neq(int x, int y);

This function returns 1 if x is not equal to y and 0 if they are equal.

You can use up to 6 of these operators:

! ~ & ^ | + << >>

Bitwise Byte #

Write a function with the following signature that takes an int x and a value n between 0 and 3 (inclusive), and returns the nth byte of x, where the 0th byte is the least significant and the 3rd is the most significant. Thus if x is 0xdeadbeef and n is 2, the function would return 0xad.

int bit_get_byte(int x, int n);

You can use up to 6 of these operators:

! ~ & ^ | + << >>

Lowest Significant Mask #

Write a function in C with the following signature:

int bit_least_set_mask(int x);

This function returns a mask of the least significant 1 bit in an integer x. Thus if x is 01100010, then the result is 00000010, and if x is 01111100, then the result is 00000100. (You’ll extend this to the full size of integers, which on this imaginary machine is 32 bits.)

You can use up to 6 of these operators:

! ~ & ^ | + << >>

Structs #

In Head First C Chapter 5, you learned about structs and the many ways to use them.

For Next Time #

  • Read Think OS Chapter 6 and do the reading quiz.
  • Start Homework 5.
  • Work on your project.