Skip to content

Instantly share code, notes, and snippets.

@hexgnu
Created June 5, 2012 21:48
Show Gist options
  • Save hexgnu/2878271 to your computer and use it in GitHub Desktop.
Save hexgnu/2878271 to your computer and use it in GitHub Desktop.
class HammingCode
attr_reader :data_bits
def initialize(number)
@number = number
@data_bits = number.to_s(2)
end
def parity_bits
indexes = []
current_index = 3
@data_bits.split(//).reverse.each do |b|
current_index += 1 if (current_index & (current_index - 1)) == 0
indexes << current_index if b == '1'
current_index += 1
end
indexes.inject(:^).to_s(2)
end
def word
pb = parity_bits.split(//).reverse
db = @data_bits.dup.split(//).reverse
output = [pb.shift, pb.shift]
until db.length == 0 && pb.length == 0
if (output.length + 1 & (output.length)) == 0
output << pb.shift
else
output << db.shift
end
end
output.reverse.join
end
end
module FailSafeBase32
extend self
Alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"
def convert(num)
output_number = ""
number = HammingCode.new(num).word.to_i(2)
while number >= 32
r = number % 32
output_number = Alphabet[r] + output_number
number /= 32
end
output_number = Alphabet[number] + output_number
output_number
end
end
require 'test/unit'
class TestHamming < Test::Unit::TestCase
Test = HammingCode.new(1301)
def test_word
assert_equal Test.word, "101000110101110"
end
def test_parity_bits
assert_equal Test.parity_bits, "1110"
end
def test_data_bits
assert_equal Test.data_bits, 1301.to_s(2)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment