在Go中将uint16强制转换为int16的正确方法 [英] Proper way for casting uint16 to int16 in Go
问题描述
按位操作和Go新手:D我正在用Go从传感器读取一些数据,并以2个字节的形式获取它-假设 0xFFFE
.也很容易将其转换为uint16,因为在Go中我们可以执行 uint16(0xFFFE)
,但是我需要将其转换为整数,因为传感器实际上返回的值范围是-32768到32767.现在我想也许Go会很不错,如果我做 int16(0xFFFE)
,它将明白我想要什么?" ,但没有.我最终使用了以下解决方案(我从网络上翻译了一些python代码):
Bitwise manipulation and Go newbie here :D I am reading some data from sensor with Go and I get it as 2 bytes - let's say 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?", but no. I ended up using following solution (I translated some python code from web):
x := 0xFFFE
if (x & (1 << 15)) != 0 {
x = x - (1<<16)
}
这似乎可行,但是A)我不确定为什么,B)我认为应该是将uint16转换为int16的简单解决方案,这看起来有点难看.谁能帮我一下,阐明为什么这是唯一的方法吗?还是还有其他可能的方法?
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. Could anyone give me a hand and clarify why this is only way to do this? Or is there any other possible way?
推荐答案
但是您想要的是,"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
.
查看可能的重复项:
这篇关于在Go中将uint16强制转换为int16的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!