如何在 Go 中将 [4]uint8 转换为 uint32?

发布于 2024-12-04 07:10:09 字数 361 浏览 1 评论 0原文

如何将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.6 && ./测试
test.go:10: 无法将 uInt8(类型 []uint8)转换为 uint32 类型

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 uint32
    uInt32 = uint32(uInt8)
    fmt.Printf("%v to %v\n", uInt8, uInt32)
}

~>6g test.go && 6l -o test test.6 && ./test
test.go:10: cannot convert uInt8 (type []uint8) to type uint32

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

往昔成烟 2024-12-11 07:10:09
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)
}

输出:

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

Go 二进制包 函数是通过一系列转换实现的。

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
}
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
}
<逆流佳人身旁 2024-12-11 07:10:09

您是否正在尝试以下

t := []int{1, 2, 3, 4}
s := make([]interface{}, len(t))
for i, v := range t {
    s[i] = v
}

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
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文