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

how to convert go type from uint8 to unit32?
Just a 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 input uint32

+6
source share
3 answers
 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) } 

Conclusion:

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

The Go function of a binary package is 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 } 
+14
source

The opposite question: how to convert uint32 to uint8 in Go?

I just want the low byte of the address. So, I answer the question. But there is no answer about this.

This question helps me a lot. I am writing my answer here.

 var x uint32 x = 0x12345678 y := uint8(x & 0xff) 

If you want to get every uint32 byte, you may need this.

 binary.BigEndian.PutUint32(buffer, Uint32Number) 
+1
source

Are you trying to do the following ?

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

Source: https://habr.com/ru/post/897099/


All Articles