[英]Convert byte slice to int slice
I'm currently trying to convert a byte
to an int
so I proceed like this:我目前正在尝试将一个
byte
转换为一个int
所以我继续这样:
var d = []byte{0x01}
val, err := strconv.Atoi(string(d))
and I get this error:我收到这个错误:
strconv.Atoi: parsing "\\x01": invalid syntax
strconv.Atoi:解析“\\x01”:语法无效
I've tried a lot of way without success yet..我已经尝试了很多方法都没有成功..
Anyone got an idea?有人有想法吗?
The slice already contains a byte value of 1
, not the ascii character 1
, so there is no need to try and convert it to a string.切片已经包含字节值
1
,而不是 ascii 字符1
,因此无需尝试将其转换为字符串。
To convert a slice of byte
to a slice of int
, convert each value individually要将
byte
切片转换为int
切片,请单独转换每个值
byteSlice := []byte{1, 2, 3, 4}
intSlice := make([]int, len(byteSlice))
for i, b := range byteSlice {
intSlice[i] = int(b)
}
For reference, see the sections on Conversions in the Go Language Specification , and in Effective Go .如需参考,请参阅Go 语言规范和Effective Go 中有关转换的部分。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.