gpt4 book ai didi

go - uint8, int8 的算术运算

转载 作者:IT王子 更新时间:2023-10-29 02:26:08 28 4
gpt4 key购买 nike

在给定示例的 unit8int8 数据类型的算术运算中得到负数和零结果的原因是什么

package main

import (
"fmt"
)

func main() {

var u uint8 = 255
fmt.Println(u, u+1, u*u) // "255 0 1"
var i int8 = 127
fmt.Println(i, i+1, i*i) // "127 -128 1"
}

https://play.golang.org/p/_a2KHP29t5p

最佳答案

Go 不会在运行时因整数溢出而 panic 。根据 doc :

For unsigned integer values, the operations +, -, *, and << are computed modulo 2n, where n is the bit width of the unsigned integer's type. Loosely speaking, these unsigned integer operations discard high bits upon overflow, and programs may rely on "wrap around".

For signed integers, the operations +, -, *, /, and << may legally overflow and the resulting value exists and is deterministically defined by the signed integer representation, the operation, and its operands. No exception is raised as a result of overflow. A compiler may not optimize code under the assumption that overflow does not occur. For instance, it may not assume that x < x + 1 is always true.

关于go - uint8, int8 的算术运算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54605650/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com