Skip to content

Instantly share code, notes, and snippets.

@silentmatt
Created June 26, 2009 17:10
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save silentmatt/136599 to your computer and use it in GitHub Desktop.
Save silentmatt/136599 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 g = gn.toString(2).split("");
var b = [];
b[0] = g[0];
for (var i = 1; i < g.length; i++) {
b[i] = g[i] ^ b[i - 1];
}
return parseInt(b.join(""), 2);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment