Module: Cabriolet::Checksum
- Defined in:
- lib/cabriolet/checksum.rb
Overview
Utility module for checksum calculations
Class Method Summary collapse
-
.calculate(data, initial = 0) ⇒ Integer
Calculate CAB-style checksum (XOR-based).
Class Method Details
.calculate(data, initial = 0) ⇒ Integer
Calculate CAB-style checksum (XOR-based)
11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 |
# File 'lib/cabriolet/checksum.rb', line 11 def self.calculate(data, initial = 0) cksum = initial bytes = data.bytes # Process 4-byte chunks (bytes.size / 4).times do |i| offset = i * 4 value = bytes[offset] | (bytes[offset + 1] << 8) | (bytes[offset + 2] << 16) | (bytes[offset + 3] << 24) cksum ^= value end # Process remaining bytes remainder = bytes.size % 4 if remainder.positive? ul = 0 offset = bytes.size - remainder case remainder when 3 ul |= bytes[offset + 2] << 16 ul |= bytes[offset + 1] << 8 ul |= bytes[offset] when 2 ul |= bytes[offset + 1] << 8 ul |= bytes[offset] when 1 ul |= bytes[offset] end cksum ^= ul end cksum & 0xFFFFFFFF end |