Golang:解析有符号整数

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

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 (
	&quot;fmt&quot;
	&quot;strconv&quot;
)

func main() {
	u, err := strconv.ParseUint(&quot;ff11223344556677&quot;, 16, 64)
	fmt.Printf(&quot;%x %v\n&quot;, u, err)
	i := int64(u)
	fmt.Println(i)
}

Output:

ff11223344556677 &lt;nil&gt;
-67234915848722825

huangapple
  • 本文由 发表于 2016年3月8日 02:35:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/35851302.html
匿名

发表评论

匿名网友

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

确定