在golang中将字符串转换为数字 [英] string to number conversion in golang
问题描述
Golang具有 strconv 库,该库将字符串转换为int64和uint64.
Golang has strconv library that converts string to int64 and uint64.
但是,其余整数数据类型似乎不受支持,因为我找不到字节,int16,uint16,int32和uint32数据类型的转换函数.
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.
始终可以从字节,16位和32位数据类型转换为int64和uint64,而不会损失精度.这是语言的意图吗?
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?
推荐答案
如果您更仔细地查看文档,则可以使用此方法;
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
bitSize
参数说明int的大小,因此您可以对 8
或 16
或 32
那些较小的整数类型. Atoi
在内部进行调用.我相信您想要 base
参数为 10
.像 b一样,err:= strconv.ParseInt("5",10,8)
表示一个字节.
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.
如果OP实际上混淆了如何将16位int转换为字符串,则只需在此处添加一些答案即可...如果这是您的预期目标,请使用 fmt.Sprintf
,或者您可以执行从较小的int到较大的int的转换,因为它将始终成功.两者的例子; https://play.golang.org/p/UWSVxEmQ1N
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; https://play.golang.org/p/UWSVxEmQ1N
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)
}
这篇关于在golang中将字符串转换为数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!