Report abuse

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# OFT Checksum calculator. 
def calc_checksum(buffer='',prev_checksum=0xffff,odd_start=false)
  checksum = (prev_checksum >> 16) & 0xffff
  buffer.split(//).each_with_index do |x,i|
    old_checksum = checksum
    # Even bytes are high, odd are low, unless the last chunk ended up starting
    # this chunk on an odd byte, in which case the reverse is true. Note that
    # the first chunk (and often the only chunk) is always starting on 0, thus,
    # even. This is the typical use case. Implementations should set the 
    # odd_start flag and the prev_checksum value if this is the case.
    if odd_start
      value = (!(i % 2).zero? ? x[0] << 8 : x[0])
    else
      value = ((i % 2).zero? ? x[0] << 8 : x[0]) # usually this one.
    end  
    checksum -= value
    checksum -= 1 if checksum > old_checksum 
  end
  2.times {checksum = (checksum & 0x0000ffff) + (checksum >> 16) }
  checksum << 16
end