将字节片转换为整数片 [英] Convert byte slice to int slice

查看:53
本文介绍了将字节片转换为整数片的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在尝试将 byte 转换为 int ,所以我这样进行:

I'm currently trying to convert a byte to an int so I proceed like this:

var d = []byte{0x01}
val, err := strconv.Atoi(string(d))

我得到这个错误:

strconv.Atoi:解析"\ x01":无效语法

strconv.Atoi: parsing "\x01": invalid syntax

我已经尝试了很多方法,但都没有成功.

I've tried a lot of way without success yet..

有人知道吗?

推荐答案

该分片已经包含 1 的字节值,而不是ascii字符 1 的字节,因此存在无需尝试将其转换为字符串.

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.

要将切片 byte 转换为切片 int ,请分别转换每个值

To convert a slice of byte to a slice of int, convert each value individually

byteSlice := []byte{1, 2, 3, 4}
intSlice := make([]int, len(byteSlice))
for i, b := range byteSlice {
    intSlice[i] = int(b)
}

作为参考,请参见转到语言规范和<一个href ="https://golang.org/doc/effective_go.html#conversions" rel ="nofollow noreferrer">有效的Go .

这篇关于将字节片转换为整数片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆