Skip to content

Instantly share code, notes, and snippets.

@dsamarin
Forked from silentmatt/graycode.js
Last active August 29, 2015 14:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dsamarin/c9b277a4a652d9a25d66 to your computer and use it in GitHub Desktop.
Save dsamarin/c9b277a4a652d9a25d66 to your computer and use it in GitHub Desktop.
JavaScript functions to convert to/from binary-reflected Gray codes
Number.toGrayCode = function(n) {
if (n < 0) {
throw new RangeError("cannot convert negative numbers to gray code");
}
return n ^ (n >>> 1);
};
Number.fromGrayCode = function(gn) {
if (gn < 0) {
throw new RangeError("gray code numbers cannot be negative");
}
var mask;
for (mask = gn >> 1; mask != 0; mask = mask >> 1) {
gn ^= mask;
}
return gn;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment