Skip to content

Instantly share code, notes, and snippets.

@denkiwakame
Created April 22, 2014 08:52
Show Gist options
  • Save denkiwakame/11170714 to your computer and use it in GitHub Desktop.
Save denkiwakame/11170714 to your computer and use it in GitHub Desktop.
graycode
#!/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