Created
June 10, 2012 18:29
-
-
Save maknoll/2906840 to your computer and use it in GitHub Desktop.
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
#!/usr/bin/ruby | |
class Integer | |
def to_b | |
Bin.new 0 == self ? [] : [self % 2] + (self / 2).to_b | |
end | |
end | |
class Bin < Array | |
def + a | |
Bin.new (0..[self.length, a.length].max - 1).map { |n| (self[n] || 0) + (a[n] || 0) } | |
end | |
def to_i | |
self.reverse.reduce { |a, n| (a << 1) + n } || 0 | |
end | |
end | |
puts (3.to_b + 15.to_b).to_i |
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
require './binadd' | |
r = Random.new 1234 | |
describe Integer, '#to_b' do | |
it 'converts a number into a binary representation' do | |
0.to_b.to_i.should eq(0) | |
10000.times do | |
n = r.rand(0..1073741823) | |
n.to_b.to_i.should eq(n) | |
end | |
end | |
end | |
describe Bin, '#+@' do | |
it 'should add two binary values' do | |
10000.times do | |
a = r.rand(0..1073741823) | |
b = r.rand(0..1073741823) | |
(a.to_b + b.to_b).to_i.should eq(a + b) | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment