Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby 如何向字符串添加校验和_Ruby_Checksum - Fatal编程技术网

Ruby 如何向字符串添加校验和

Ruby 如何向字符串添加校验和,ruby,checksum,Ruby,Checksum,我不确定这样问是否正确。如何将校验和算法集成到标签字符串中。我研究过奇偶校验字节,但并不真正理解按位运算符(XOR)。我只需要字符串的单个字符散列 class Integer def to_bin(width) '%0*b' % [width, self] end sequence_id = 1.to_bin(24) library = '3467ACDEFGHJKMNP' prefix = library[12] label = prefix + sequence_id.scan

我不确定这样问是否正确。如何将校验和算法集成到
标签
字符串中。我研究过奇偶校验字节,但并不真正理解按位运算符(XOR)。我只需要字符串的单个字符散列

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

sequence_id = 1.to_bin(24)
library = '3467ACDEFGHJKMNP'

prefix = library[12]

label = prefix + sequence_id.scan(/\d{4}/).reverse.each_with_object(String.new) do |n,obj|
    obj << library[n.to_i(2)]
end

p sequence_id
p label

end
类整数
def至_箱(宽度)
“%0*b”%[宽度,自]
结束
序列号=1。到地址(24)
库='3467ACDEFGHJKMNP'
前缀=库[12]
label=prefix+sequence_id.scan(/\d{4}/).reverse.每个带有_对象(String.new)的_都做| n,obj|
obj我确信在字符串的右边添加校验和不是一个好主意。因为你必须自己控制某种分隔符。例如,我下面的代码有明显的错误,如果原始字符串包含冒号
字符,它将无法工作

下一点是实施。我认为,在你成为数值计算专家之前,最好避免自己实现这些算法。最好的方法是使用现有的东西,比如MD5和CRC32。我认为MD5对于这项任务来说相当繁重,所以让我们使用

以下是代码:

require 'zlib'

# This is sample string
strings = ['Hello', 'World', '!']
# Create array where each element
# has original string folowed by colon
# and CRC32 of original string
strings_with_crc = strings.collect do |string|
  string + ':' + Zlib.crc32(string).to_s
end

# Now we can check it!
def crc32check(array)
  array.each do |e|
    string, crc32 = e.split(':')
    print "Checking '#{string}' with '#{crc32}' crc32 sum... "
    puts Zlib.crc32(string) === crc32.to_i ? 'Ok.' : 'FAIL!'
  end
end

puts "Checkin just created array with correct sums:"
crc32check(strings_with_crc)

puts "Checkin new array with wrong sum:"
crc32check(["Hello:42", "World:4223024711", "!:123456"])
以下是脚本的输出:

签入刚刚创建的带有和的数组。

正在使用“4157704578”crc32总和检查“Hello”。。。好啊
正在使用“4223024711”crc32总和检查“World”。。。好啊
检查“!”与'2657877971'crc32汇总。。。好的。

使用错误的sum签入新数组。

正在使用“42”crc32总和检查“Hello”。。。失败!
正在使用“4223024711”crc32总和检查“World”。。。好啊

检查“!”与“123456”crc32合计。。。失败

所需的输出是什么?
摘要::MD5.hexdigest(字符串)