CS341 - Intro. to Computer Architecture and Organization - Professor Ackley

Tuesday and Thursday: 9:30am - 10:45am (Centennial 1028) Lab: Friday 2:00pm - 2:50pm (Centennial B146)

Bit Twiddling

Goals

  • Learn some cool bit tricks
  • Implement some in Y86

//TODO

Go ahead and write your answers (in Y86) to each problem on a sheet of paper. Answers should be generalized and work in every case. BE EXACT when it comes to syntax for Y86!

#1. Check if integer is odd.

Let's start off with an easy one. What operation could we use? Are there multiple ways to arrive at this answer? Which is more efficient?

#2. Turn off the rightmost 1-bit.

i.e. 00111000 would be 00110000.
There are 2 possible scenarios:

  1. There are no 1's in the integer (all 0).
  2. There is at least one 1 set in the integer. The rightmost one needs to be flipped while the others stay the same.
HINT: AND-ing with yourself keeps each bit the same. AND-ing zeros with ones, keeps the zeros.

#3. Isolate the rightmost 1-bit.

Find the rightmost 1-bit and set all others to 0. i.e. 01101100 would be 00000100.
This is an awesome little trick. Remember that with two's compliment, -x = ~x+1 where ~x is the invert of each bit of x. Since all bits to the right of the right most 1-bit would be flipped to 1 (since the invert of 0 is 1), adding 1 to that value will carry the one back to the right most 1-bit. Therefore, what could we AND with to make this happen?

#4. Isolate the rightmost 0-bit.

Find the rightmost 0-bit, set it to 1, and set all others to 0. i.e. 01101101 would be 00000010.
This is the opposite of #3.

#5. Turn on the rightmost 0-bit.

Find the rightmost 0-bit, set it to 1. i.e. 01101101 would be 01101111.
OR-ing x with x+1 does not lose any information. Adding 1 to x fills the first rightmost 0.


//SOLUTIONS

I highly recommend trying to figure out the above 5 tricks by thinking about bit manipulation. However, here are the answers as to how each are done: Answers. *NOTE: This isn't the Y86 answer, just the bit-wise ops.


Turn-in

Hand me a sheet of paper with as much as you can get done before you leave.