Skip to content

Instantly share code, notes, and snippets.

@socantre
Created February 12, 2015 17:00
Show Gist options
  • Save socantre/7195124b25ae6abd7d22 to your computer and use it in GitHub Desktop.
Save socantre/7195124b25ae6abd7d22 to your computer and use it in GitHub Desktop.
#include <iostream>
#include <random>
#include <cassert>
#include <cstdint>
static int odd_bits(std::uint64_t i) {
auto a = (0xFFFFFFFFu & i) ^ (i >> 32);
auto b = (0x0000FFFFu & a) ^ (a >> 16);
auto c = (0x000000FFu & b) ^ (b >> 8);
auto d = (0x0000000Fu & c) ^ (c >> 4);
auto e = (0x00000003u & d) ^ (d >> 2);
auto f = (0x00000001u & e) ^ (e >> 1);
return f;
}
static int parity(std::uint64_t i) {
return odd_bits(i & 0xFFFFFFFF00000000u) << 5 |
odd_bits(i & 0xFFFF0000FFFF0000u) << 4 |
odd_bits(i & 0xFF00FF00FF00FF00u) << 3 |
odd_bits(i & 0xF0F0F0F0F0F0F0F0u) << 2 |
odd_bits(i & 0xCCCCCCCCCCCCCCCCu) << 1 |
odd_bits(i & 0xAAAAAAAAAAAAAAAAu) << 0;
}
static std::uint64_t flip_bit(std::uint64_t i, int bit) {
return i ^ (1ull << bit);
}
int main() {
std::mt19937 eng;
std::uniform_int_distribution<std::uint64_t> dist;
std::uniform_int_distribution<int> rand_parity(0, 63);
std::cout << std::hex;
for (int i = 0; i < 10; ++i) {
auto x = dist(eng);
std::cout << x << ' ' << parity(x) << " : ";
auto b = rand_parity(eng);
auto y = flip_bit(x, parity(x) ^ b);
std::cout << b << " : ";
std::cout << y << ' ' << parity(y) << '\n';
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment