[ create a new paste ] login | about

Link: http://codepad.org/lRQsixgC    [ raw code | output | fork ]

programmingpraxis - C, pasted on Aug 19:
/* 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;

}


Output:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
37
84
37
84

0
1
1
0
1
0

84 37
84 37


Create a new paste based on this one


Comments: