golang成长记

golang标准库binary学习

2018-07-05  本文已影响0人  Tim_SSS

简介

Package binary implements simple translation between numbers and byte sequences and encoding and decoding of varints.

The varint functions encode and decode single integer values using a variable-length encoding; smaller values require fewer bytes.For a specification, see https://developers.google.com/protocol-buffers/docs/encoding.


翻译:binary 包,简单的实现了数字和byte之间的转化;varints之间的编码和解码。简单说一下,varints是一种使用一个或多个字节表示整型数据的方法。其中数值本身越小,其所占用的字节数越少。


使用

Numbers are translated by reading and writing fixed-size values.A fixed-size value is either a fixed-size arithmetic type (bool, int8, uint8, int16, float32, complex64, ...)or an array or struct containing only fixed-size values.


翻译:通过读入和写入固定长度的值来转化数字。固定长度的值,既可以是指定长度的值,也可以是指定长度数组,也可以是包含指定长度结构体。数字类型必须申明为,bool, int8, uint8, int16, float32, complex64, ...,具体可以去看源码


package main
import (
"bytes"
"encoding/binary"
"fmt"
)
func main() {
    by := []byte{0x00, 0x00, 0x03, 0xe8}
    var num int32
    bytetoint(by, &num)
    fmt.Println(int(num), num)

    // 测试 int -> byte
    by2 := []byte{}
    var num2 int32
    num2 = 333
    by2 = inttobyte(&num2)
    fmt.Println(by2)

    // 测试 byte -> int
    var num3 int32
    bytetoint(by2,&num3)
    fmt.Println(num3)
}
// byte 转化 int
func bytetoint(by []byte, num *int32)  {
    b_buf := bytes.NewBuffer(by)
    binary.Read(b_buf, binary.BigEndian, num)
}
// 数字 转化 byte
func inttobyte(num *int32) []byte {
    b_buf := new(bytes.Buffer)
    binary.Write(b_buf, binary.BigEndian,num)
    return b_buf.Bytes()
}
上一篇下一篇

猜你喜欢

热点阅读