Skip to content

Instantly share code, notes, and snippets.

@dustinbrownman
Created August 29, 2013 16:26
Show Gist options
  • Select an option

  • Save dustinbrownman/6380333 to your computer and use it in GitHub Desktop.

Select an option

Save dustinbrownman/6380333 to your computer and use it in GitHub Desktop.
Converts a binary (or trinary) number string to decimal. There's only one character difference between the two functions (besides the exceptions).
def binary(binary_string)
if !(binary_string.is_a?(String)) || binary_string.match(/[^0,1]/)
raise TypeError.new("Input must be only 0s and 1s")
end
total = 0
binary_string.reverse.split("").each_with_index do |bit, index|
total += bit.to_i * 2 ** index
end
total
end
def trinary(trinary_string)
if !(trinary_string.is_a?(String)) || trinary_string.match(/[^0,1,2]/)
raise TypeError.new("Input must be only 0s and 1s and 2s")
end
total = 0
trinary_string.reverse.split("").each_with_index do |bit, index|
total += bit.to_i * 3 ** index
end
total
end
require 'rspec'
require 'binary'
describe 'binary' do
it 'converts 0 in binary to 0' do
binary("0").should eq 0
end
it 'converts longer binary bits' do
binary("101").should eq 5
end
it 'raises an exception if it gets a non-binary number' do
expect { binary("12") }.to raise_exception
end
end
describe 'trinary' do
it 'converts trinary numbers to decimal' do
trinary("1021").should be 34
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment