Skip to content

golang技巧

Go语言中的数值溢出检测

package main

import (
    "fmt"
    "math"
)

func addInt8WithOverflowCheck(a, b int8) (int8, bool) {
    result := a + b
    // 使用异或运算检测溢出
    overflow := (a^result)&(b^result) < 0
    return result, overflow
}

func main() {
    a := int8(-127)
    b := int8(-1)
    result, overflowed := addInt8WithOverflowCheck(a, b)
    if overflowed {
        fmt.Println("溢出发生,结果:", result)
    } else {
        fmt.Println("结果:", result)
    }
}

Comments