Created
October 25, 2017 17:56
-
-
Save jiafulow/0c8c0874c726c8bee8ebd4afe7f7d3a0 to your computer and use it in GitHub Desktop.
C++ Gray code
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// Code from "Numerical Recipe in C (2nd edition)" by Press et al. | |
// Chapter 20.2 pg.896 | |
// | |
#include <cstdint> | |
#include <iostream> | |
// Return the Gray code of n | |
uint64_t gray(uint64_t n) | |
{ | |
// This is the easy direction! | |
return (n ^ (n >> 1)); | |
} | |
// Return the inverse Gray code of n | |
uint64_t inverse_gray(uint64_t n) | |
{ | |
// This is the more complicated direction: In hierarchical | |
// stages, starting with a one-bit right shift, cause each | |
// bit to be XORed with all more significant bits. | |
int ish = 1; | |
uint64_t ans = n; | |
uint64_t idiv = 0; | |
for (;;) { | |
idiv = (ans >> ish); | |
ans ^= idiv; | |
if (idiv <= 1 || ish == 16) | |
return ans; | |
ish <<= 1; | |
} | |
return ans; | |
} | |
int main () | |
{ | |
for (int i = 0; i < 64; i++) { | |
// Convert i to Gray code, and then convert it back | |
std::cout << i << " " << gray(i) << " " << inverse_gray(gray(i)) << std::endl; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment