Created
September 30, 2012 23:55
-
-
Save mikepack/3808771 to your computer and use it in GitHub Desktop.
Binary Add
This file contains hidden or 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
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