-
-
Save dsamarin/c9b277a4a652d9a25d66 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 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