mardi 9 juillet 2024

32-bit Integer overflow

We often get error messages related to overflow. This is annoying, because the code is interrupted and for Red beginners, it's not always easy to understand the nature of the errors. A classic example is overflow when you multiply 2 32-bit integers and the result exceeds the minimum or maximum integer value supported by Red (-2147483648 or 2147483648).

You will find 2 functions (Red/System and Red) that are an attempt to solve this type of problem.

First with Red/System

Red/System [

Author:  "ldci"
]
;--system/cpu/overflow? checks if the last integer math operation has overflown.
;--as many CPU operations can change this state, it is only reliable if used immediatly after the math operation.
isMulOverflow?: func [
"function to multiply two integers and check for overflow"
a [integer!]
b [integer!]
return: [logic!]
][
    a * b ;--Perform the multiplication
    system/cpu/overflow? ;--Immediately return the cpu overflow status
]
;--tests
print-wide ["1000 * 70000   overflow?:" isMulOverflow? 1000 70000 lf]
print-wide ["740000 * 70000 overflow?:" isMulOverflow? 740000 70000 lf]

And now with Red

Red [
]
isMulOverflow?: func [
a [integer!]
b [integer!]
return: [logic!]
] [
if ((a = 0) or (b = 0)) [return false]
attempt [result:  a * b] 
either a = (result / b) [return false] [return true] 
]
;--tests
print ["1000 * 5000 Overflow?:"    isMulOverflow? 1000 5000]
print ["-1000 * 1000 Overflow?:"   isMulOverflow? -1000 1000]
print ["740000 * 70000 Overflow?:" isMulOverflow? 740000 70000]





Aucun commentaire:

Enregistrer un commentaire