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, p⊗p=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,b∈Fn2 a=a⊗0=a⊗b⊗bb=0⊗b=a⊗a⊗b 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
b = a % 16;
Note that 16=24, so we mask it with the bit sequence 1111=15=(F)16, obtaining
b = (a / 8) * 8;
This effectively zeroes the lowest 3 bits. I could either
- And-mask the lowest 3 bits then bitwise xor;
- Shift right, then shift left.
Which is better?
4 Bit twiddling
$s0 = 0x8000001F
$s0 = 0x0AAAAAAA
- For every 1 in the sequence
$s0
∈F322, it toggles the MSB of$s0
.
5 Loop through array
Tracing. In iterations…
- First iteration. t1←M[112]=108s1←0+108=108t0←M[4+112]=M[116]=124
- Second iteration. t1←M[124]=104s1←108+104=212t0←M[4+124]=M[128]=100
- Third iteration. t1←M[100]=120s1←212+120=332t0←M[4+100]=M[104]=132
Set M[104]←0 will cause it to terminate.
“High-level” code
or in pointer notation,