Go Signed int overflow detection

I am creating Lisp and I want 32-bit integers to automatically switch to 64-bit integers if the calculation leads to their overflow. Similarly, for 64-bit overflows, switch to integers of arbitrary size.

The problem is that I do not know what the β€œcorrect” way to detect integer overflows.

a, b := 2147483647, 2147483647 c := a + b 

How can I effectively check if c is full?

I always considered converting to 64-bit values ​​for computation, and then reduce the size after that whenever possible, but it seems expensive, and memory is wasteful for something that is primitive and core to the language as basic arithmetic.

+8
go integer-overflow
source share
1 answer

For example, to detect a 32-bit integer overflow to add,

 package main import ( "errors" "fmt" "math" ) var ErrOverflow = errors.New("integer overflow") func Add32(left, right int32) (int32, error) { if right > 0 { if left > math.MaxInt32-right { return 0, ErrOverflow } } else { if left < math.MinInt32-right { return 0, ErrOverflow } } return left + right, nil } func main() { var a, b int32 = 2147483327, 2147483327 c, err := Add32(a, b) if err != nil { // handle overflow fmt.Println(err, a, b, c) } } 

Output:

 integer overflow 2147483327 2147483327 0 
+5
source share

All Articles