type-conversion – 如何在Go中将[4] uint8转换为uint32?

前端之家收集整理的这篇文章主要介绍了type-conversion – 如何在Go中将[4] uint8转换为uint32?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
如何将go的类型从uint8转换为unit32?
只需代码
package main

import (
    "fmt"
)

func main() {
    uInt8 := []uint8{0,1,2,3}
    var uInt32 uint32
    uInt32 = uint32(uInt8)
    fmt.Printf("%v to %v\n",uInt8,uInt32)
}

〜> 6g test.go&& 6l -o test test.6&& ./测试
test.go:10:无法将uInt8(类型[] uint8)转换为uint32类型

package main

import (
    "encoding/binary"
    "fmt"
)

func main() {
    u8 := []uint8{0,3}
    u32LE := binary.LittleEndian.Uint32(u8)
    fmt.Println("little-endian:",u8,"to",u32LE)
    u32BE := binary.BigEndian.Uint32(u8)
    fmt.Println("big-endian:   ",u32BE)
}

输出

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

Go binary package功能实现为一系列转换.

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
}
原文链接:https://www.f2er.com/windows/364636.html

猜你在找的Windows相关文章