[REBOL] Re: checksum calculation
From: antonr:iinet:au at: 11-Sep-2003 17:48
Well, what have you got so far?
I suppose your algorithm in rebol doesn't match the
one in C?
(Just refreshing my memory, ~3 in C just means
get the bitwise inverse of 3, that means all
bits on except bit 0 and bit 1.)
I presume the ((Length+3) & ~3) is so that the length
(in bytes) is truncated at a four byte boundary, which
makes sure that you have the last ULONG.
How does your table data look in rebol?
What is the byte-order for each ULONG ?
calc-table-checksum: func [table [binary!] /local sum length pos][
sum: 0 ; (signed long integer)
length: (and~ 3 (3 + length? table)) / 4 ; ULONG = 4 bytes
; step through the table data in chunks of four bytes
repeat n length [
pos: n * 4
; (I don't know if this byte order is correct)
val: to-integer rejoin [# (table/:pos) (pick table pos + 1)
(pick table pos + 2) (pick table pos + 3)]
; catch math overflow
sum: either error? try [sum + val][
; which way did it overflow? (positive/negative)
either positive? sum [
; overflowed in positive direction
; to-integer required because -2147483648 is by default a decimal
(sum + to-integer -2147483648) + (val + to-integer -2147483648)
; overflowed in negative direction
(2147483647 + sum) + (2147483647 + val) + 2
][sum + val] ; no error, just add it up
probe type? sum
; a negative final sum (signed long) is converted to decimal by the
either positive? sum [sum][sum + (2 * 2147483648)]
The above is not fully tested.
I quickly tested the overflow code, and it seems to be ok.
Getting the table data out in the right order remains to be tested.