[REBOL] Re: subtracting binaries
From: antonr:lexicon at: 2-Apr-2004 3:16
I was helping Oldes with the problem of computing
a long checksum a while back. The code I came up with
is at the bottom. It can give you some ideas maybe.
Anton.
> Hi,
>
> As anybody (efficiently) tackled suntracting two binary! values. I want
> to compute the difference between two 160 bit SHA1 keys, with the
> outcome a new binary. And I also need addition which sould be circular
> in 160bit space. E.g 2^160 + 1 = 1
>
> Before re-inventing yet another wheel I'd thought I'd ask to see if
> anybody has already written this.
>
> --Maarten
; can use pairs to store integers better and wrap around automatically
; without math overflow error! :) (Romano's tip)
sum: 2147483647
add-val: func [val][
sum: either error? try [sum + val][
; which way did it overflow? (positive/negative)
either positive? sum [
print "positive"
; overflowed in positive direction
; to-integer required because -2147483648 is by default a decimal
;print ["(sum + to-integer -2147483648):" (sum + to-integer -2147483648)
type? (sum + to-integer -2147483648)]
;print ["(val + to-integer -2147483648):" (val + to-integer -2147483648)
type? (val + to-integer -2147483648)]
(sum + to-integer -2147483648) + (val + to-integer -2147483648)
][
print "negative"
; overflowed in negative direction
(2147483647 + sum) + (2147483647 + val) + 2
]
][sum + val] ; no error, just add it up
probe type? sum
sum
]