Trying to and from bases in Ruby... the code I've laid out seems quite repetitious. Is ther a better way?
module Converter def self.convert(value, from, to) case from when :hex case to when :dec # code to change hex to dec when :oct # code to change hex to oct when :bin # code to change hex to bin when :ascii # code to change hex to ascii end when :dec case to when :hex # code to change dec to hex when :oct # code to change dec to oct when :bin # code to change dec to bin when :ascii # code to change dec to ascii end when :oct case to when :hex # code to change oct to hex when :dec # code to change oct to dec when :bin # code to change oct to bin when :ascii # code to change oct to ascii end when :bin case to when :hex # code to change bin to hex when :dec # code to change bin to dec when :oct # code to change bin to oct when :ascii # code to change bin to ascii end when :ascii case to when :hex # code to change ascii to hex when :dec # code to change ascii to dec when :oct # code to change ascii to oct when :bin # code to change ascii to bin end end end end
In decimal to binary, we divide the number by 2, in decimal to hexadecimal we divide the number by 16. In case of decimal to octal, we divide the number by 8 and write the remainders in the reverse order to get the equivalent octal number.
ASCII (American Standard Code for Information Interchange) is the most common character encoding format for text data in computers and on the internet. In standard ASCII-encoded data, there are unique values for 128 alphabetic, numeric or special additional characters and control codes.
Below are the implementation of both methods: Using ASCII values: ASCII value of uppercase alphabets – 65 to 90. ASCII value of lowercase alphabets – 97 to 122.
class String def convert_base(from, to) self.to_i(from).to_s(to) # works up-to base 36 end end p '1010'.convert_base(2, 10) #=> "10" p 'FF'.convert_base(16, 2) #=> "11111111"
Come up with code to convert from anything to decimal and from decimal to anything and then combine those. E.g. to convert from binary to hex, convert to decimal first and then that to hex. Base conversion is also trivial to implement in a generic way that can handle any base, given the set of digits it uses.
Also, please remember that a numeric value in memory doesn't really have the concept of a base (it's represented as binary, obviously, but that's mostly irrelevant). It's just a value. Only once you get strings involved do bases become really significant. So if your "decimal" really means a numeric value instead of a string of digits, it might be best to not call it "decimal".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With