英文:
Golang: parse a signed int
问题
我有一些代码,需要能够将包含64位值的字符串解析为int64类型。例如,ff11223344556677
是有效的,但下游系统希望将其作为int64
类型处理。
strconv.ParseInt("ff11223344556677", 16, 64)
会产生一个范围错误 - 它只能解析正整数。有没有办法将这个值转换为int64类型,即使它是负数?
英文:
I have some code that needs to be able to parse a string containing a 64-bit value into an int64. For example, ff11223344556677
is valid, but a downstream system wants that in an int64
.
strconv.ParseInt("ff11223344556677", 16, 64)
gives a range error - it only likes to parse positive integers. Is there a way to go about putting this value into an int64 even though it is going to be negative?
答案1
得分: 5
例如,
package main
import (
"fmt"
"strconv"
)
func main() {
u, err := strconv.ParseUint("ff11223344556677", 16, 64)
fmt.Printf("%x %v\n", u, err)
i := int64(u)
fmt.Println(i)
}
输出:
ff11223344556677 <nil>
-67234915848722825
英文:
For example,
package main
import (
"fmt"
"strconv"
)
func main() {
u, err := strconv.ParseUint("ff11223344556677", 16, 64)
fmt.Printf("%x %v\n", u, err)
i := int64(u)
fmt.Println(i)
}
Output:
ff11223344556677 <nil>
-67234915848722825
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论