Converting Hex to signed Int in Go

huangapple go评论150阅读模式
英文:

Converting Hex to signed Int in Go

问题

我想在Go语言中将一个十六进制字符串转换为有符号整数值。我的输入值是"FF60",我希望输出结果是"-160"。当我使用下面的函数时,结果是"65376",它表示的是无符号表示。

value, err := strconv.ParseInt("FF60", 16, 64)

我本来期望使用ParseUInt函数时的结果是65376。
非常感谢任何帮助。

英文:

I want to convert a hex string to a signed integer Value in Go. My input value is "FF60" and I want the output to be "-160". When I use the following function, the result is "65376", which represents the unsigned representation.

value, err := strconv.ParseInt("FF60", 16, 64)

I would have expected the outcome of 65376 when using the ParseUInt function.
Any help would be really appreciated.

答案1

得分: 3

strconv.ParseInt()的第三个参数指定了你想解析的整数的位数。将0xff60解析为64位整数确实是65376

实际上,你想将其解析为16位整数,所以将16作为位数传递进去。但这样做会导致错误:

strconv.ParseInt: parsing "FF60": value out of range

这是正确的:0xFF60(即65376)超出了int16的有效范围(有效的int16范围是[-32768..32767])。

因此,你可以使用strconv.ParseUint()将其解析为无符号16位整数,然后将结果转换为有符号16位整数:

value, err := strconv.ParseUint("FF60", 16, 16)
fmt.Println(value, err)
fmt.Println(int16(value))

这将输出(在Go Playground上尝试):

65376 <nil>
-160
英文:

The third parameter of strconv.ParseInt() tells the bitsize of the integer you want to parse. 0xff60 parsed as a 64-bit integer is indeed 65376.

You actually want to parse it as a 16-bit integer, so pass 16 as the bitsize. Doing so you will get an error though:

strconv.ParseInt: parsing &quot;FF60&quot;: value out of range

Which is true: 0xFF60 (which is 65376) is outside of the valid range of int16 (valid int16 range is [-32768..32767]).

So what you may do is parse it as an unsigned 16-bit integer using strconv.ParseUint(), then convert the result to a signed 16-bit integer:

value, err := strconv.ParseUint(&quot;FF60&quot;, 16, 16)
fmt.Println(value, err)
fmt.Println(int16(value))

This will output (try it on the Go Playground):

65376 &lt;nil&gt;
-160

huangapple
  • 本文由 发表于 2022年5月10日 21:02:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/72186838.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定