2.34. Calculating a 32-Bit CRCThe 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. |