Created
April 22, 2014 08:52
-
-
Save denkiwakame/11170714 to your computer and use it in GitHub Desktop.
graycode
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
#!/usr/bin/ruby | |
def toGrayCode(binary) | |
return binary ^ (binary >> 1) | |
end | |
def binaryStr(num) | |
binaryStr = "" | |
while num > 0 | |
binaryStr = String(num & 1) + binaryStr | |
num >>= 1 | |
end | |
return binaryStr | |
end | |
def Gray2Binary(num) | |
tmp=0 | |
tmp |= num | |
while num > 0 | |
num >>= 1 | |
tmp ^= num | |
end | |
return tmp | |
end | |
NUM = 100 | |
NUM.times do |i| | |
gc = toGrayCode(i) | |
if i == Gray2Binary(gc) | |
puts "#{i}...#{binaryStr(gc)}...ok" | |
else | |
puts "#{i}...NOT OK" | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment