Skip to content

Instantly share code, notes, and snippets.

@mikepack
Created September 30, 2012 23:55
Show Gist options
  • Save mikepack/3808771 to your computer and use it in GitHub Desktop.
Save mikepack/3808771 to your computer and use it in GitHub Desktop.
Binary Add
class BinaryPlus
def initialize(first, second)
@first, @second = first, second
# to_s accepts a base to convert to. In this case, base 2.
@first_bin = @first.to_s(2)
@second_bin = @second.to_s(2)
normalize
end
def +
carry = '0'
result_bin = ''
@max_size.times do |i|
# We want to work in reverse, from the rightmost bit
index = @max_size - i - 1
first_bit, second_bit = @first_bin[index], @second_bin[index]
if first_bit == '1' and second_bit == '1'
result_bin << carry
carry = '1'
else
if first_bit == '1' or second_bit == '1'
if carry == '1'
result_bin << '0'
# carry remains 1
else
result_bin << '1'
carry = '0'
end
else
result_bin << carry
carry = '0'
end
end
end
# Is there still a carry hangin' around?
result_bin << '1' if carry == '1'
result_bin.reverse.to_i(2)
end
private
def normalize
# We want both binary numbers to have the same length
@max_size = @first_bin.size < @second_bin.size ? @second_bin.size : @first_bin.size
@first_bin = @first_bin.rjust(@max_size, '0')
@second_bin = @second_bin.rjust(@max_size, '0')
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment