Last active
August 29, 2015 14:07
-
-
Save danvonk/0d3fca788b0bcc755d31 to your computer and use it in GitHub Desktop.
base no. algo
This file contains 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/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