Skip to content

Instantly share code, notes, and snippets.

@realeroberto
Created November 3, 2016 14:03
Show Gist options
  • Save realeroberto/05b74777c1868297dc33665ab9495627 to your computer and use it in GitHub Desktop.
Save realeroberto/05b74777c1868297dc33665ab9495627 to your computer and use it in GitHub Desktop.
Convert an integer to its Gray-code representation.
#
# 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