Golang Standard library Binary learning

Source: Internet
Author: User

Brief introduction

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.

Translation: binary packet, simple implementation of the conversion between the number and byte, varints between the encoding and decoding. To put it simply, Varints is a way to represent integer data using one or more bytes. The smaller the value itself, the less the number of bytes it occupies.

Use

    • Conversion of numbers and bytes to each other

Numbers is 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 a array or struct containing only fixed-size values.

Translation: Converts a number by reading in and writing a fixed-length value. A fixed-length value that can be a value of a specified length, a specified length array, or a structure containing a specified length. The number type must be stated as, BOOL, int8, Uint8, Int16, float32, complex64, ..., specific to see the source code

package mainimport ("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 转化 intfunc bytetoint(by []byte, num *int32)  {    b_buf := bytes.NewBuffer(by)    binary.Read(b_buf, binary.BigEndian, num)}// 数字 转化 bytefunc inttobyte(num *int32) []byte {    b_buf := new(bytes.Buffer)    binary.Write(b_buf, binary.BigEndian,num)    return b_buf.Bytes()}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.