string to number conversion in golang

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

string to number conversion in golang

问题

Golang有一个名为strconv的库,可以将字符串转换为int64和uint64。

然而,其他整数数据类型似乎不受支持,因为我找不到byte、int16、uint16、int32和uint32数据类型的转换函数。

可以始终将byte、16位和32位数据类型转换为int64和uint64,而不会丢失精度。这是否是语言的意图?

英文:

Golang has strconv library that converts string to int64 and uint64.

However, the rest of integer data types seems to be unsupported as I can't find conversion functions for byte, int16, uint16, int32, uint32 data types.

One can always convert from byte, 16-bit and 32-bit data types to int64 and uint64 without loss of precision. Is that what's intended by language?

答案1

得分: 7

如果你仔细查看文档,可以使用以下方法:

func ParseInt(s string, base int, bitSize int)

https://golang.org/pkg/strconv/#ParseInt

bitSize 参数表示整数的大小,因此你可以使用 81632 来表示较小的整数类型。Atoi 在内部调用了这个方法。我认为你想要将 base 参数设置为 10。例如,对于一个字节,可以这样写:b, err := strconv.ParseInt("5", 10, 8)

编辑:为了解决可能存在的将 16 位整数转换为字符串的困惑,我在答案中添加了一些内容。如果这是你的目标,你可以使用 fmt.Sprintf 或将较小的整数转换为较大的整数,因为它总是会成功。这里有两个示例:

package main

import "fmt"
import "strconv"

func main() {
    var a int16
    a = 5
    s := fmt.Sprintf("%d", a)
    s2 := strconv.Itoa(int(a))
    fmt.Println(s)
    fmt.Println(s2)
}
英文:

If you look at the docs a bit more closely you can use this method;

func ParseInt(s string, base int, bitSize int)

https://golang.org/pkg/strconv/#ParseInt

The bitSize argument says how large the int is so you can do 8 or 16 or 32 for those smaller integer types. Atoi calls this internally. I believe you're wanting 10 for the base argument. So like b, err := strconv.ParseInt("5", 10, 8) for a byte.

EDIT: Just going to add a couple things to the answer here in case the OP is in fact confused how to convert a 16-bit int into a string... If that is your intended goal just use fmt.Sprintf or you can do a conversion from smaller int to larger int as it will always succeed. Examples of both here;

package main

import "fmt"
import "strconv"

func main() {
	var a int16
	a = 5
	s := fmt.Sprintf("%d", a)
	s2 := strconv.Itoa(int(a))
	fmt.Println(s)
	fmt.Println(s2)
}

答案2

得分: 3

例如,

package main

import (
	"fmt"
	"strconv"
)

func main() {
	n := int16(42)
	s := strconv.FormatInt(int64(n), 10)
	fmt.Printf("n %d s %q\n", n, s)
}

输出:

n 42 s "42"
英文:

For example,

package main

import (
	"fmt"
	"strconv"
)

func main() {
	n := int16(42)
	s := strconv.FormatInt(int64(n), 10)
	fmt.Printf("n %d s %q\n", n, s)
}

Output:

n 42 s "42"

答案3

得分: 3

你可以使用fmt.Sprintf()方法将任何int类型转换为字符串。

var num int64
numstring := fmt.Sprintf("%d", num)
英文:

You can convert any int type to string using fmt.Sprintf() method

var num int64
numstring:=fmt.Sprintf("%d",num)

huangapple
  • 本文由 发表于 2015年10月15日 00:37:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/33130949.html
匿名

发表评论

匿名网友

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

确定