编写一个检查校验和算法的ruby方法

时间:2014-12-03 16:27:14

标签: ruby methods checksum

我使用K + 6 + 1(前缀+代码+校验和)格式创建字符串。我想编写一个方法来检查我的label并验证校验和算法是否正确。我不确定如何解决这个问题。

require 'benchmark'

class Integer
    def to_bin(width)
        '%0*b' % [width, self]
    end
end

integer_number = 1
binary_number = integer_number.to_bin(24)
dictionary = '3467ACDEFGHJKMNP'
prefix = 'K'

code = ''
checksum = ''
label = ''

p '================ A1 ================'

Benchmark.bm do |x|
    x.report do
        parity = 0
        binary_number.scan(/\d{4}/).reverse.each_with_index do |item, index|
            word = item.to_i(2)
            parity = index == 0 ? word : parity ^ word
            code += dictionary[item.to_i(2)]
        end

        checksum = dictionary[parity]
        label = prefix + code + checksum
    end
end

0 个答案:

没有答案