Skip to content

Instantly share code, notes, and snippets.

@maknoll
Created June 10, 2012 18:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save maknoll/2906840 to your computer and use it in GitHub Desktop.
Save maknoll/2906840 to your computer and use it in GitHub Desktop.
#!/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
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