codepad
[
create a new paste
]
login
|
about
Language:
C
C++
D
Haskell
Lua
OCaml
PHP
Perl
Plain Text
Python
Ruby
Scheme
Tcl
/* more bit hacks */ #include <stdio.h> int main(void) { int x, y; /* 1) Compute the minimum (or maximum) of two integers without branching */ x = 37; y = 84; printf("%d\n", y ^ ((x ^ y) & -(x < y))); // min printf("%d\n", x ^ ((x ^ y) & -(x < y))); // max x = 84; y = 37; printf("%d\n", y ^ ((x ^ y) & -(x < y))); // min printf("%d\n", x ^ ((x ^ y) & -(x < y))); // max printf("\n"); /* 2) Determine if an integer is a power of two */ x = 37; printf("%d\n", (x & (x - 1)) == 0); x = 32; printf("%d\n", (x & (x - 1)) == 0); x = 0; printf("%d\n", (x & (x - 1)) == 0); x = 37; printf("%d\n", x && !(x & (x - 1))); x = 32; printf("%d\n", x && !(x & (x - 1))); x = 0; printf("%d\n", x && !(x & (x - 1))); printf("\n"); /* 3) Swap the values of two variables */ #define SWAP(a, b) (((a) ^= (b)), ((b) ^= (a)), ((a) ^= (b))) x = 37; y = 84; SWAP(x, y); printf("%d %d\n", x, y); #define SWAP(a, b) (((a) -= (b)), ((b) += (a)), ((a) = (b) - (a))) x = 37; y = 84; SWAP(x, y); printf("%d %d\n", x, y); return 0; }
Private
[
?
]
Run code
Submit