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

huangapple go评论76阅读模式
英文:

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

问题

如何将Go语言中的类型从uint8转换为uint32?
只需修改代码如下:

package main

import (
    "fmt"
)

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

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

英文:

how to convert go's type from uint8 to unit32?<br/>
Just code:

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

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

答案1

得分: 16

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)
}

英文:
package main

import (
	&quot;encoding/binary&quot;
	&quot;fmt&quot;
)

func main() {
	u8 := []uint8{0, 1, 2, 3}
	u32LE := binary.LittleEndian.Uint32(u8)
	fmt.Println(&quot;little-endian:&quot;, u8, &quot;to&quot;, u32LE)
	u32BE := binary.BigEndian.Uint32(u8)
	fmt.Println(&quot;big-endian:   &quot;, u8, &quot;to&quot;, 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])&lt;&lt;8 | uint32(b[2])&lt;&lt;16 | uint32(b[3])&lt;&lt;24
}

func (bigEndian) Uint32(b []byte) uint32 {
	return uint32(b[3]) | uint32(b[2])&lt;&lt;8 | uint32(b[1])&lt;&lt;16 | uint32(b[0])&lt;&lt;24
}

答案2

得分: -1

你是否试图实现以下代码?

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
}

huangapple
  • 本文由 发表于 2011年9月12日 01:52:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/7380158.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定