EPI 5.3 BIT REVERSAL

#include 
#include 
using namespace std;

long long swap_bits(long long x, int i, int j) {
    if (((x >> i) & 1) != ((x >> j) & 1)) {
        x ^= (1LL << i) | (1LL << j);
    }
    return x;
}

long long reverse_x(long long x, int n) {
    for (int i = 0, j = n; i < j; i++, j--) {
        x = swap_bits(x, i, j);
    }
    return x;
}

long long precomputed_reverse[1 << 16];

long long reverse_bits(long long x) {
    return precomputed_reverse[x & 0xffff] << 48 |
           precomputed_reverse[(x >> 16) & 0xffff] << 32 |
           precomputed_reverse[(x >> 32) & 0xffff] << 16 |
           precomputed_reverse[(x >> 48) & 0xffff];
}

int main(int argc, char *argv[]) {
    for (int i = 0; i < (1 << 16); i++) {
        precomputed_reverse[i] = reverse_x(i, 15);
    }
    srand(time(nullptr));
    if (argc == 2) {
        long long n = atol(argv[1]);
        assert(reverse_x(n, 63) == reverse_bits(n));
        cout << "n = " << n << ", reverse = " << reverse_bits(n) << endl;
    } else {
        for (int i = 0; i < 100; i++) {
            long long n = rand();
            assert(reverse_x(n, 63) == reverse_bits(n));
            cout << "n = " << n << ", reverse = " << reverse_bits(n) << endl;
        }
    }
    return 0;
}

你可能感兴趣的:(EPI)