如何将 int[] 转换为 uint8[] [英] How to convert int[] to uint8[]

查看:51
本文介绍了如何将 int[] 转换为 uint8[]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,我需要你的帮助.我找不到有关该主题的任何内容.Golang 是一门新鲜出炉的语言,所以像我这样的新手很难快速找到答案.

SO, I need your help. I couldn’t find anything on that topic. Golang is a freshly baked language so it’s quite hard to find answers quick for a newcomers like me.

推荐答案

预先声明的 Go int 类型大小是特定于实现的,32 位或 64 位(数字类型).

The predeclared Go int type size is implementation-specific, either 32 or 64 bits (Numeric types).

这是一个将大端ints 转换为bytes (uint8s) 的例子.

Here's an example of converting big-endian ints to bytes (uint8s).

package main

import (
    "encoding/binary"
    "fmt"
    "reflect"
)

func IntsToBytesBE(i []int) []byte {
    intSize := int(reflect.TypeOf(i).Elem().Size())
    b := make([]byte, intSize*len(i))
    for n, s := range i {
        switch intSize {
        case 64 / 8:
            binary.BigEndian.PutUint64(b[intSize*n:], uint64(s))
        case 32 / 8:
            binary.BigEndian.PutUint32(b[intSize*n:], uint32(s))
        default:
            panic("unreachable")
        }
    }
    return b
}

func main() {
    i := []int{0, 1, 2, 3}
    fmt.Println("int size:", int(reflect.TypeOf(i[0]).Size()), "bytes")
    fmt.Println("ints:", i)
    fmt.Println("bytes:", IntsToBytesBE(i))
}

输出:

int size: 4 bytes
ints: [0 1 2 3]
bytes: [0 0 0 0 0 0 0 1 0 0 0 2 0 0 0 3]

int size: 8 bytes
ints: [0 1 2 3]
bytes: [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 2 0 0 0 0 0 0 0 3]

这篇关于如何将 int[] 转换为 uint8[]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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