Skip to content

Instantly share code, notes, and snippets.

@193s
Created July 9, 2015 08:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 193s/52cf7628825b23525233 to your computer and use it in GitHub Desktop.
Save 193s/52cf7628825b23525233 to your computer and use it in GitHub Desktop.
unsigned long tempering(unsigned long y) {
/* Tempering */
y ^= (y >> 11);
y ^= (y << 7) & 0x9d2c5680UL;
y ^= (y << 15) & 0xefc60000UL;
y ^= (y >> 18);
return y;
}
unsigned long TemperingMaskB = 0x9d2c5680;
unsigned long TemperingMaskC = 0xefc60000;
unsigned long undoTemperShiftL(unsigned long y) {
unsigned long last14 = y >> 18;
unsigned long fin = y ^ last14;
return fin;
}
unsigned long undoTemperShiftT(unsigned long y) {
unsigned long first17 = y << 15;
unsigned long fin = y ^ (first17 & TemperingMaskC);
return fin;
}
unsigned long undoTemperShiftS(unsigned long y) {
/*
* This one also sucked to figure out, but now I think i could write
* a general one. This basically waterfalls and keeps restoring original
* bits then shifts the values down and xors again to restore more bits
* and keeps on doing it.
*/
unsigned long a = y << 7;
unsigned long b = y ^ (a & TemperingMaskB);
unsigned long c = b << 7;
unsigned long d = y ^ (c & TemperingMaskB); // now we have 14 of the original
unsigned long e = d << 7;
unsigned long enc_key = y ^ (e & TemperingMaskB); // now we have 21 of the original
unsigned long g = enc_key << 7;
unsigned long h = y ^ (g & TemperingMaskB); // now we have 28 of the original
unsigned long i = h << 7; // now we have the original xor
unsigned long fin = y ^ (i & TemperingMaskB);
return fin;
}
unsigned long undoTemperShiftU(unsigned long y) {
/*
* This was confusing to figure out.
* We know the first 11 bits are un-altered becuase they were
* xored with 0's. We shift those 11 bits to the right and xor that with the
* original which gives us the first 22 bits(b) of what it orginally was. Now that we have the
* first 22 bits so we can shift that to the right 11 bits which gives us
* what the number was orginally xored with. So then we just xor y with that and
* our number is restored!
*/
unsigned long a = y >> 11;
unsigned long b = y ^ a;
unsigned long c = b >> 11;
unsigned long fin = y ^ c;
return fin;
}
unsigned long reverse_tempering(unsigned long y) {
y = undoTemperShiftL(y);
y = undoTemperShiftT(y);
y = undoTemperShiftS(y);
y = undoTemperShiftU(y);
return y;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment