06-25-2014, 05:58 PM
(This post was last modified: 06-25-2014, 06:43 PM by redstonewarrior.)
Quote:b * 0x0101010101010101ULLYou lied to us.
Some fun ones from an assignment a while back:
Code:
// Absolute value of an integer. Uses bitmasking fun!
int absVal(int x) {
int mask = x >> 0x1F;
return (mask ^ x) + (mask & 1);
}
// Determines if one number is greater than the other, using only basic
// operations and addition. __Works correctly given over/underflow conditions.__
// Uses only 9 operations. I'm proud of this baby, I beat 100+ people with it.
int isGreater(int x, int y) {
int difference = y + ~x + 1; // y - x. Positive if y > x || overflow.
int xor = ((y ^ difference) & (x ^ y));
// -1 iff sign of x != sign of y (difference could OF.)
return 1 & ((xor ^ (difference)) >> 31);
}
// Another function for identifying powers of two. Works correctly for Two's Complement numbers, I.E. 0x80 won't trigger.
int isPower2(int x) {
int maskd = x >> 31;
int sub = x & (x + ~maskd);
return !(sub | !x); // Edge cases.
}
// More informally, parity can be done without any multiplication / other shenanigans.
// This implementation should be / probably is faster on most CPUs.
Parity:
int a = x;
a ^= a >> 1;
a ^= a >> 2;
a ^= a >> 4;
// Continue logarithmically for wider words...
return a & 1;
All of these functions are written using only assignment, bitwise operators, left/right shift, and addition. There is no control logic, function calls, etc.
:3