且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在Go中将uint16强制转换为int16的正确方法

更新时间:2022-11-29 16:50:54

但是您想要的是,"Go很好":

But what you want works, "Go is nice":

ui := uint16(0xFFFE)
fmt.Println(ui)
i := int16(ui)
fmt.Println(i)

输出(在游乐场上尝试):

65534
-2

int16(0xFFFE)不起作用,因为 0xfffe 是一个无类型的整数常量,不能用 int16 类型的值表示,这就是编译器抱怨的原因.但是您当然可以将任何 uint16 非恒定值转换为 int16 .

int16(0xFFFE) doesn't work because 0xfffe is an untyped integer constant which cannot be represented by a value of type int16, that's why the the compiler complains. But you can certainly convert any uint16 non-constant value to int16.

查看可能的重复项:

Golang:故意的int溢出

可以使用编译器的常量表达式和其他表达式的评估方式不同