Created
November 3, 2016 14:03
-
-
Save realeroberto/05b74777c1868297dc33665ab9495627 to your computer and use it in GitHub Desktop.
Convert an integer to its Gray-code representation.
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
# | |
# convert an integer to its Gray-code representation | |
# | |
Add-Type -TypeDefinition @' | |
public class shift { | |
public static int lshift(int x, int count) { return x << count; } | |
public static int rshift(int x, int count) { return x >> count; } | |
} | |
'@ | |
function intToGray([Byte] $x, [Int] $numBits) | |
{ | |
# compute Gray code | |
[Byte] $y = $x -bxor ([shift]::rshift($x, 1)) | |
# convert to a base-2 string representation | |
[String] $gray = [convert]::ToString([Int] $y, 2) | |
# pad with 0's | |
$gray = "{0:D$numBits}" -f [Int] $gray | |
return $gray | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment