Skip to content

Instantly share code, notes, and snippets.

@danvonk
Last active August 29, 2015 14:07
Show Gist options
  • Save danvonk/0d3fca788b0bcc755d31 to your computer and use it in GitHub Desktop.
Save danvonk/0d3fca788b0bcc755d31 to your computer and use it in GitHub Desktop.
base no. algo
#!/usr/bin/env ruby
#Convert a binary value to decimal...
x = 1011
n = Math.log10(x).to_i + 1
b = 2 #binary
s = 0
x.to_s.chars.map(&:to_i).each do |u|
n = n - 1
value = u * b ** n
s = s + value
end
puts "Result from binary is #{s}"
#Convert a hex value to decimal...
alphabet = ["A", "B", "C", "D", "E", "F"]
x = "9F"
n = x.length
b = 16 #base 16
s = 0
x.split("").each do |u|
#decrement the digit count by 1
n = n -1
if u.match /[A-Za-z]/
hex = 9 + (alphabet.index(u) + 1)
s = s + hex * (b ** n)
else
s = s + u.to_i * (b ** n)
end
end
puts "Result from hex is #{s}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment