#56 Challenge - Bit Manipulation in C

Credits: Computer Systems: A Programmer's Perspective
Authors: Randal E. Bryant and David R. O'Hallaron
Samples of book: http://csapp.cs.cmu.edu/public/manuscript.html
Disclaimer: I have written permission from the author to post his labs on my site.

Required files for this challenge: datalab.tar.gz

In this challenge your goal is to edit a series of functions in bits.c to mimic the behavior of bit Ands, Nors, etc... with restrictions to what operators you can use.

One of the functions in the bits.c code is:



/*


 * bitAnd - x&y using only ~ and |


 *   Example: bitAnd(6, 5) = 4


 *   Legal ops: ~ |


 *   Max ops: 8


 *   Rating: 1


 */


int bitAnd(int x, int y) {


  return 2;


}



For the above code we want to return the value of x bitwise AND y with using only ~ and |
For this function we can solve it by doing ~(~x|~y).

Then our solution would look like.



/*


 * bitAnd - x&y using only ~ and |


 *   Example: bitAnd(6, 5) = 4


 *   Legal ops: ~ |


 *   Max ops: 8


 *   Rating: 1


 */


int bitAnd(int x, int y) {


  return ~(~x|~y);


}



And we check our solution by recompiling and running this function on the test driver.



linux > make clean; make btest


linux > ./btest -f bitAnd


Test bitAnd score: 1.00/1.00


Overall correctness score: 1.00/1.00


All tests passed.



If you want to test all the functions at once just type ./btest

Each time you make changes to bits.c you must run make btest.