简体   繁体   English

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

[英]Proper way for casting uint16 to int16 in Go

Bitwise manipulation and Go newbie here :DI am reading some data from sensor with Go and I get it as 2 bytes - let's say 0xFFFE . 按位操作和Go新手在这里:DI正在使用Go从传感器读取一些数据,我将其获取为2个字节-假设0xFFFE It is easy too cast it to uint16 since in Go we can just do uint16(0xFFFE) but what I need is to convert it to integer, because the sensor returns in fact values in range from -32768 to 32767. Now I thought "Maybe Go will be this nice and if I do int16(0xFFFE) it will understand what I want?" 也很容易将其强制转换为uint16,因为在Go中我们可以执行uint16(0xFFFE)但我需要将其转换为整数,因为传感器返回的值实际上是-32768到32767。现在,我想“也许Go会很不错,如果我执行int16(0xFFFE) ,它将明白我想要什么吗?” , but no. , 但不是。 I ended up using following solution (I translated some python code from web): 我最终使用了以下解决方案(我从网络上翻译了一些python代码):

x := 0xFFFE

if (x & (1 << 15)) != 0 {
    x = x - (1<<16)
}

It seems to work, but A) I am not entirely sure why, and B) It looks a bit ugly to what I imagined should be a trivial solution for casting uint16 to int16. 它似乎可行,但是A)我不确定为什么,B)我认为应该是将uint16转换为int16的简单解决方案,这看起来有点难看。 Could anyone give me a hand and clarify why this is only way to do this? 谁能帮我一下,弄清楚为什么这是唯一的方法? Or is there any other possible way? 还是还有其他可能的方法?

But what you want works, "Go is nice": 但是您想要的是,“ Go很好”:

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

Output (try it on the Go Playground ): 输出(在Go Playground上尝试):

65534
-2

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. int16(0xFFFE)不起作用,因为0xfffe是无类型整数常数不能由类型的值来表示int16 ,这就是为什么该编译器会抱怨。 But you can certainly convert any uint16 non-constant value to int16 . 但是您当然可以将任何uint16非恒定值转换为int16

See possible duplicates: 查看可能的重复项:

Golang: on-purpose int overflow Golang:故意int溢出

Does go compiler's evaluation differ for constant expression and other expression 对于常量表达式和其他表达式,去编译器的评估是否有所不同

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM