Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 516
YBW Avatar asked Sep 11 '11 17:09

YBW


People also ask

How to convert string* into string in Go?

You can convert numbers to strings by using the strconv. Itoa method from the strconv package in the Go standard libary. If you pass either a number or a variable into the parentheses of the method, that numeric value will be converted into a string value.

What is the difference between uint8 and int8?

Differences between signed and unsigned types are- int8 can take values from -127 to 128, and uint8 - from 0 to 255. * means a number, that indicates the size of this numeric type from 8 to 256.

What is uint8 in Golang?

type uint8 in Golang is the set of all unsigned 8-bit integers. The set ranges from 0 to 255. You should use type uint8 when you strictly want a positive integer in the range 0-255. Below is how you declare a variable of type uint8 : var var_name uint8.


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

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
}
like image 142
peterSO Avatar answered Sep 24 '22 00:09

peterSO