Converting from ]uint to ]byte in Golang

Asked 2 years ago, Updated 2 years ago, 49 views

I would like to convert the variable in [ ]uint to [ ]byte.
Is there a good solution...?

go

2022-09-30 12:03

1 Answers

As the questions are unclear, the answers will vary depending on the results.

As Nobonobo said, please convert it into a loop

package main

import(
    "fmt"
)

func UintSliceToByteSlice(us[]uint)[]byte{
    b:=make([]byte,len(us))
    for i,v: = range us {
        b[i] = byte(v)
    }
    return b
}

funcmain(){
    u: = [ ] uint {1,2,3}

    b: = UintSliceToByteSlice(u[:])
    fmt.Println(b)
}

The result is 1, 2, 3, and 4 bytes slices.

It depends on the endian.The results depend on how uint (uint32 or uint64) is stored in memory.The following is an example of a Big Endian used as a network byte order:

package main

import(
    "bytes"
    "encoding/binary"
    "fmt"
    "log"
)

funcmain(){
    u: = [ ] uint {1,2,3,4}

    var buf bytes.Buffer
    for_,v: = range u {
        err —=binary.Write (&buf,binary.BigEndian,uint32(v))
        if err!=nil{
            log.Fatal(err)
        }
    }
    fmt.Println(buf.Bytes())
}

The result is [00 0 1 0 2 0 3 0 4 ].The size of uint varies depending on the platform, so if you can decide the size from the beginning, you can write it as follows.

package main

import(
    "bytes"
    "encoding/binary"
    "fmt"
    "log"
)

funcmain(){
    u: = [ ] uint32 {1,2,3,4}

    var buf bytes.Buffer
    err: = binary.Write (&buf,binary.BigEndian,u)
    if err!=nil{
        log.Fatal(err)
    }
    fmt.Println(buf.Bytes())
}


2022-09-30 12:03

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.