Skip to content

Instantly share code, notes, and snippets.

@dentarg
Created October 21, 2010 16:28
Show Gist options
  • Select an option

  • Save dentarg/638812 to your computer and use it in GitHub Desktop.

Select an option

Save dentarg/638812 to your computer and use it in GitHub Desktop.
Some functions to convert binary to hex and vice versa
#!/usr/local/bin/ruby
# bin functions
def bin2dec(str)
return eval("0b#{str}.to_i")
end
def bin2hex(str)
return "todo"
end
# dec functions
def dec2bin(str)
dec = str.to_i
array = Array.new(8)
array = Array.new(16) if dec>255
for i in 1..array.size
array[i] = dec % 2
dec = dec/2
end
return array.reverse.to_s
end
def dec2hex(str)
return "todo"
end
# hex functions
def hex2bin(str)
return dec2bin(hex2dec(str))
end
def hex2dec(str)
return str.hex
end
# print function
def my_print(bin, dec, hex)
puts "#{bin}\t#{dec}\t#{hex}"
end
# num functions
def bin(str)
bin = dec2bin(bin2dec(str))
dec = bin2dec(str)
hex = bin2hex(str)
my_print(bin, dec, hex)
end
def dec(str)
bin = dec2bin(str)
dec = str
hex = dec2hex(str)
my_print(bin, dec, hex)
end
def hex(str)
bin = hex2bin(str)
dec = hex2dec(str)
hex = str
my_print(bin, dec, hex)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment