英文:
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 "FF60": 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("FF60", 16, 16)
fmt.Println(value, err)
fmt.Println(int16(value))
This will output (try it on the Go Playground):
65376 <nil>
-160
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论