This is a creation in Article, where the information may have evolved or changed.
The following is the use of standard library binary to encode and decode
Decoding
① Use bytes. Newreader/bytes. Buffer to store the ASCII string to decode
② uses binary. Read to decode
package mainimport ( "bytes" "encoding/binary" "FMT") Func main () { var pi float64 bpi := []byte{0x18, 0x2d, 0x44, 0x54, 0xfb, 0x21, 0x09, 0x40} buf := bytes. Newreader (BPI) err := binary. Read (buf, binary. LITTLEENDIAN, &PI) // Here you can continue to read out the existence of variables, so that you can decode a lot of, read order and variable type to // binary. Read (buf, binary. LITTLENDIAN, &V2) if err != nil { fmt. Println ("Binary. read failed: ", err) } fmt. Print (PI) // 3.141592653589793}
Coding
① Use bytes. Buffer to store the string generated by the encoding
② uses binary. Write to encode the buf stored in the ①
Package Mainimport ("bytes" "Encoding/binary" "FMT") func main () {var pi float64 = 3.141592653589793 buf: = new (bytes. Buffer) Err: = Binary. Write (buf, Binary. Littleendian, PI)//here can continue to write in buf, there are buf//binary. Write (buf, Binary. Littleendian, UInt16 (12345)) if err! = Nil {fmt. Println ("Binary. Read failed: ", err)} FMT. Print (BUF. Bytes ())//[24 45 68 84 251 33 9 64]}
Multi mode
Decoding
Ing
Coding
package mainimport ( "bytes" "Encoding/binary" "FMT") Func main () { buf := new (bytes. Buffer) var data = []interface{}{ uint16 (61374), int8 ( -54), uint8 (254), } for _, v := range data { err := binary. Write (buf, binary. LITTLEENDIAN, V) if err != nil { fmt. Println ("Binary. write failed: ", err) } } fmt. Printf ("%x", Buf. Bytes ()) // beefcafe This is a string of 16 binary strings // here converted to 16 binary integers?}