Ancient CS 61 Content Warning!!!!!1!!!
This is not the current version of the class.
This site was automatically translated from a wiki. The translation may have introduced mistakes (and the content might have been wrong to begin with).

Lecture 3 Notes: Computer Arithmetic

Announcements

Unsigned Arithmetic

Our discussion of unsigned arithmetic will involve the following C types:

Historical Digression

Concepts

One of the most important concepts of unsigned arithmetic is the following:

What about subtraction? Remember that unsigned computer arithmetic is the same as mathematical arithmetic modulo 2^w. Using the laws of regular arithmetic, t a-b should be the same as a+-b. That's just a mathematical law. What does that say about -b? How do we represent it in unsigned arithmetic?

What else is 0 mod 2^w? 2^w. This says that c = 2^w - b. Doesn't look like we've solved anything, but this is mathematical subtraction, not unsigned, modulus subtraction, since we have bounds on c. So what's -1? 2^w - 1. Note that, 2^w - 1 + 1 = 2^w = 0. That's the definition of -1: when we add 1 to it, we should get 0, and in computer arithmetic, we do!

Fun

Strictly speaking, in math, if x > 0, then -x < x. However, what about computer math, for unsigned numbers? We know that -x is representable. But they're not in any specific relationship.

Is there a time when 􀀀x == x for x! = 0? Yes, solve by finding an x so that 2x == 0. That can be (2^w)/2 , or 2^(w-1), another "interesting" number!

Operations on C Integers

More Fun

What is (x|y) - (x&y)? Answer: (x∪y). One explanation: Take the bits that all the bits that are lit up, and then take away the bits that are lit up in both places. You have left only the bits in positions that are lit up in exactly one number.

Scribe's explanation: Imagine this in terms of probabilities: if you calculate the probability of events x or y occurring, you've found the probability that x occurs, y occurs, or x and y occurs. To find the probability that exactly one of these events occurs, just subtract the intersection, x&y!

A Bit About Sets

Let's see if we can use bits to construct a representation of a set that supports the following operations:

Suggestion: An array of bits: where 0 means it's not in the set, and 1 means it's in the set. How many letters are there? 26! What fits in 26 - an unsigned int! We can represent sets of up to 32 objects in terms of bits. Very cheap operations!

Signed Arithmetic