Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Decoding data from a byte slice to Uint32

Tags:

go

package main

import (
        "bytes"
        "encoding/binary"
        "fmt"
)

func main() {
        aa := uint(0xFFFFFFFF)
        fmt.Println(aa)
        byteNewbuf := []byte{0xFF, 0xFF, 0xFF, 0xFF}
        buf := bytes.NewBuffer(byteNewbuf)
        tt, _ := binary.ReadUvarint(buf)
        fmt.Println(tt)
}

Need to convert 4 bytes array to uint32 but why the results are not same ? go verion : beta 1.1

like image 407
Pole_Zhang Avatar asked Apr 06 '13 08:04

Pole_Zhang


People also ask

How do you convert bytes to strings?

One method is to create a string variable and then append the byte value to the string variable with the help of + operator. This will directly convert the byte value to a string and add it in the string variable.

How do you convert a byte array into a string?

There are two ways to convert byte array to String: By using String class constructor. By using UTF-8 encoding.

Which of the following ways is correct to convert a byte into long object in Java?

Method 2: Using BigInteger.

What is byte in Golang?

The byte type in Golang is an alias for the unsigned integer 8 type ( uint8 ). The byte type is only used to semantically distinguish between an unsigned integer 8 and a byte. The range of a byte is 0 to 255 (same as uint8 ).


1 Answers

You can do this with one of the ByteOrder objects from the encoding/binary package. For instance:

package main

import (
        "encoding/binary"
        "fmt"
)

func main() {
        aa := uint(0x7FFFFFFF)
        fmt.Println(aa)
        slice := []byte{0xFF, 0xFF, 0xFF, 0x7F}
        tt := binary.LittleEndian.Uint32(slice)
        fmt.Println(tt)
}

If your data is in big endian format, you can instead use the same methods on binary.BigEndian.

like image 133
James Henstridge Avatar answered Oct 07 '22 06:10

James Henstridge