How to convert [4]uint8 into uint32 in Go?

前端 未结 2 519
清酒与你
清酒与你 2021-02-14 08:06

how to convert go\'s type from uint8 to unit32?
Just code:

package main

import (
    \"fmt\"
)

func main() {
    uInt8 := []uint8{0,1,2,3}
    var uInt32          


        
相关标签:
2条回答
  • 2021-02-14 08:10

    Are you trying to the following?

    t := []int{1, 2, 3, 4}
    s := make([]interface{}, len(t))
    for i, v := range t {
        s[i] = v
    }
    
    0 讨论(0)
  • 2021-02-14 08:36
    package main
    
    import (
        "encoding/binary"
        "fmt"
    )
    
    func main() {
        u8 := []uint8{0, 1, 2, 3}
        u32LE := binary.LittleEndian.Uint32(u8)
        fmt.Println("little-endian:", u8, "to", u32LE)
        u32BE := binary.BigEndian.Uint32(u8)
        fmt.Println("big-endian:   ", u8, "to", u32BE)
    }
    

    Output:

    little-endian: [0 1 2 3] to 50462976
    big-endian:    [0 1 2 3] to 66051
    

    The Go binary package functions are implemented as a series of shifts.

    func (littleEndian) Uint32(b []byte) uint32 {
        return uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24
    }
    
    func (bigEndian) Uint32(b []byte) uint32 {
        return uint32(b[3]) | uint32(b[2])<<8 | uint32(b[1])<<16 | uint32(b[0])<<24
    }
    
    0 讨论(0)
提交回复
热议问题