2014-12-03 54 views
2

我不確定這是否是正確的詢問方式。如何將校驗和算法集成到我的label字符串中。我研究過奇偶校驗字節,但並不真正瞭解按位運算符(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 
+0

期望的輸出是什麼? – Anthony 2014-12-03 01:53:28

+0

'Digest :: MD5.hexdigest(string)'? – 2014-12-03 02:25:13

回答

1

我敢肯定它是不添加校驗右邊是字符串好主意。因爲你必須自己控制某種分離器。例如我的代碼下面有明顯的錯誤,如果原始字符串包含冒號:字符,它將不起作用。

下一點是執行。我認爲,最好避免自己實現這樣的算法,直到你成爲數字計算的專家。最好的辦法是使用現有的東西,如MD5CRC32。我認爲MD5是針對任務相當繁重,讓我們用CRC32

這裏是代碼:

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"]) 

下面是腳本的輸出:

Checkin just created array with sums. Checking 'Hello' with '4157704578' crc32 sum... Ok. Checking 'World' with '4223024711' crc32 sum... Ok. Checking '!' with '2657877971' crc32 summ... Ok.

Checkin new array with wrong summ. Checking 'Hello' with '42' crc32 sum... FAIL! Checking 'World' with '4223024711' crc32 sum... Ok. Checking '!' with '123456' crc32 sum... FAIL!