Created
June 26, 2009 17:10
-
-
Save silentmatt/136599 to your computer and use it in GitHub Desktop.
JavaScript functions to convert to/from binary-reflected Gray codes
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
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