go - 转换负数

标签 go

当将负数转换为无符号整数并稍后添加该值时,它会导致减去。

a := (uint8)(10)
b := (int8)(-8)
fmt.Println(a + (uint8)(b)) // result: 2

这是一种惯用的方法还是应该更明确地完成?

最佳答案

由于类型是无符号的,所以它是一个 overflow :
uint8(b)248,所以 a + uint8(b)10+248=258=> 255 0 1 2 => 2

my question is more about how to subtract from unsigned integers when the value (sometimes you want to add and sometimes subtract) is coming from an argument (that must be a signed type) which makes it so that you have to do type conversion before subtracting/adding.

同时使用 int8:


    a := int8(10)
    b := int8(-8)
    fmt.Println(a + b) // 2
    fmt.Println(a - b) // 18

您可以避免溢出,例如 this :

    a := uint8(10)
    b := int8(-8)
    c := uint8(b)
    d := uint16(a) + uint16(c)
    fmt.Println(d) // 258

你应该删除这里多余的括号:

a := (uint8)(10)
b := (int8)(-8)
fmt.Println(a + (uint8)(b))

使用这个:

a := uint8(10)
b := int8(-8)
fmt.Println(a + uint8(b))

参见:
confusion about convert `uint8` to `int8`

关于go - 转换负数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56714851/

相关文章:

debugging - Go - 编译一组函数时出错

go - 如何在 labstack echo session 中间件中获得相同的 session ?

go - 如何打包 golang 测试助手代码?

web-services - 使用 gin-gonic 编写 Web 服务的最佳实践是什么

go - 为什么命令 "go clean -n -r -i github.com/ethereum/go-ethereum..."不起作用?

go - 在 Go 中查找结构的底层匿名字段类型

go - 通过 go 函数的参数返回值,该函数是从 C 调用的

go - 后台打印程序概念/API 和 channel : issue passing jobs to a queue from serveHTTP

go - 如何在beego中获取controller之外的cookie和session

golang 公共(public)方法到私有(private)结构 - 这有任何用例吗