将数据从字节片解码到Uint32 [英] Decoding data from a byte slice to Uint32

查看:52
本文介绍了将数据从字节片解码到Uint32的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

需要将4个字节的数组转换为uint32,但为什么结果不相同?go verion:beta 1.1

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

推荐答案

您可以使用 encoding/binary 包中的 ByteOrder 对象之一来执行此操作.例如:

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

如果数据采用大端格式,则可以对 binary.BigEndian 使用相同的方法.

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

这篇关于将数据从字节片解码到Uint32的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆