我敢肯定它是不添加校驗右邊是字符串好主意。因爲你必須自己控制某種分離器。例如我的代碼下面有明顯的錯誤,如果原始字符串包含冒號:
字符,它將不起作用。
下一點是執行。我認爲,最好避免自己實現這樣的算法,直到你成爲數字計算的專家。最好的辦法是使用現有的東西,如MD5和CRC32。我認爲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!
期望的輸出是什麼? – Anthony 2014-12-03 01:53:28
'Digest :: MD5.hexdigest(string)'? – 2014-12-03 02:25:13