CS2100 Tutorial 2

Qi Ji

Week 4

1 Bitwise ops

trivial.

2 Swapping

Let denote coordinate-wise XOR in Fn2. Notice that (Fn2,) forms an Abelian group, where for any vector p, pp=0, that is every element is its own inverse. Additionally, 0 is the identity element. Therefore, to swap two bits, first note that for any a,bFn2 a=a0=abbb=0b=aab so in code

void swap(int *a, int *b) {
    *a ^= *b;   // *a = a ^ b
    *b ^= *a;   // *b = a ^ b ^ b = a ^ 0 = a
    *a ^= *b;   // *a = a ^ b ^ a = b ^ 0 = b
}

an alternative is using + since machines do addition modulo Z/2wZ.

3 Bit masks

  1. b = a % 16;

    Note that 16=24, so we mask it with the bit sequence 1111=15=(F)16, obtaining

    andi   $s1, $s0, 0xF
  2. b = (a / 8) * 8;

    This effectively zeroes the lowest 3 bits. I could either

    • And-mask the lowest 3 bits then bitwise xor;
    andi    $t0, $s0, 0x7       # lowest 3 bits go to $t0
    xor     $s1, $s0, $t0
    • Shift right, then shift left.
    srl     $s1, $s0, 3
    sll     $s1, $s1, 3

    Which is better?

4 Bit twiddling

    1. $s0 = 0x8000001F
    2. $s0 = 0x0AAAAAAA
  1. For every 1 in the sequence $s0 F322, it toggles the MSB of $s0.

5 Loop through array

  1. Tracing. In iterations…

    1. First iteration. t1M[112]=108s10+108=108t0M[4+112]=M[116]=124
    2. Second iteration. t1M[124]=104s1108+104=212t0M[4+124]=M[128]=100
    3. Third iteration. t1M[100]=120s1212+120=332t0M[4+100]=M[104]=132
  2. Set M[104]0 will cause it to terminate.

  3. “High-level” code

int t0 = 112, t1, s1 = 0;
while (t0 != 0) {
    t1 = M[t0];
    s1 += t1;
    t0 = M[t0+1];
}

or in pointer notation,

int *t0 = 112, t1, s1 = 0;
while (t0 != 0) {
    t1 = *t0;
    s1 += t1;
    t0 = *(t0+1);
}