Section 2.35. Calculating the MD5 Hash of a String

2.34. Calculating a 32-Bit CRC

The Cyclic Redundancy Checksum (CRC) is a well-known way of obtaining a "signature" for a file or other collection of bytes. The CRC has the property that the chance of data being changed and keeping the same CRC is 1 in 2**N, where N is the number of bits in the result (most often 32 bits).

The zlib library, created by Ueno Katsuhiro, enables you to do this.

The method crc32 computes a CRC given a string as a parameter:

require 'zlib' include Zlib crc = crc32("Hello")             # 4157704578 crc = crc32(" world!",crc)       # 461707669 crc = crc32("Hello world!")      # 461707669 (same as above)

A previous CRC can be specified as an optional second parameter; the result will be as if the strings were concatenated and a single CRC was computed. This can be used, for example, to compute the checksum of a file so large that we can only read it in chunks.

The Ruby Way(c) Solutions and Techniques in Ruby Programming
The Ruby Way, Second Edition: Solutions and Techniques in Ruby Programming (2nd Edition)
ISBN: 0672328844
EAN: 2147483647
Year: 2004
Pages: 269
Authors: Hal Fulton

Similar book on Amazon © 2008-2017.
If you may any questions please contact us: