This is not the current version of the class.

Data representation 6: Assertions and arenas

This lecture started out with a 30-minute discussion of assertion style. We referred to the CS 61 Style Guide several times, and the concept of “Goldilocks assertions”: not too many, not too few. A concrete question was raised about unused functions; the [[maybe_unused]] attribute was introduced.

Example 1: Signed integer overflow

int x_incr = x + 1;
assert(x_incr > x);
printf("assertion passed, so %d > %d\n", x_incr, x);

Sanitizer to the rescue

$ make SAN=1 signedoverflow
...
$ ./signedoverflow 2147483647
signedoverflow.cc:16:9: runtime error: signed integer overflow: 2147483647 + 1 cannot be represented in type 'int'

Sanitizers and undefined behavior

Using computer arithmetic for good

Truth tables

~ output
0 1
1 0
& 0 1
0 0 0
1 0 1
| 0 1
0 0 1
1 1 1
^ 0 1
0 0 1
1 1 0

Beware precedence

Some mathematical properties

Left and right shift

Properties of bitwise arithmetic

Fun with bits

Using bits

Bitset example

WTF corner

(You don’t need to understand this, but it is fun!)

unsigned long wtf(unsigned long x) {
    unsigned long y = x & -x;
    unsigned long c = x + y;
    return (((x ^ c) >> 2) / y) | c;
}

Bit twiddling hacksGosper’s hack