Created
September 30, 2011 19:35
-
-
Save fabrizioc1/1254756 to your computer and use it in GitHub Desktop.
Number base conversion
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
# Converts from base 10 to a different base | |
def get_digit(digit) | |
digit.to_i > 9 ? sprintf("%0X",digit.to_i) : digit.to_s | |
end | |
def to_base(input,new_base) | |
raise "Number base should be between 2 and 16!" if ((new_base > 16) || (new_base < 2)) | |
raise "Input number must be an unsigned integer!" if (input < 0) | |
return 0 if input == 0 | |
output = '' | |
current = input | |
max = Math.log(current)/Math.log(new_base) | |
max = max.truncate | |
pow = max | |
index = max | |
while index >= 0 do | |
digit = current / (new_base ** index) | |
if (digit >= new_base) | |
raise "Digit must be between 0 and #{new_base-1} for numbers in base #{new_base}" | |
end | |
character = sprintf("%X",digit.to_i) | |
output << character | |
#current = input % (digit*(new_base ** pow)) if digit>0 | |
current = current - (digit*(new_base ** index)) | |
index = index - 1 | |
end | |
return output | |
end | |
# Test | |
# 202000001112112 b3 = 10629941 b10 | |
def from_base(input,base) | |
output = 0 | |
index = 0 | |
while index <= input.to_s.length-1 do | |
character = input.to_s[index..index] | |
if (character !~ /[0-9A-Za-z]/) | |
raise "Illegal digit found '#{character}' in '#{input}!" | |
end | |
digit = (character =~ /[A-Za-z]/) ? sprintf("%d","0x#{character}").to_i : character.to_i | |
if (digit >= base) | |
raise "Digits must be between 0 and #{base-1} for numbers in base #{base}" | |
end | |
power = (input.to_s.length - 1) - index | |
value = digit * (base ** power) | |
output = output + value | |
index = index + 1 | |
end | |
return output | |
end | |
# Add new to_i() to class String | |
class String | |
def to_d(base) | |
from_base(to_s,base) | |
end | |
end | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment