Get the App
SLTechnology News&Howtos  ›  Servers  › 

What is the conversion between Go language structure and binary array

Shulou Source: shulou.com Published: 2022-05-31 23:02:21 09月22日 Update

This article shows you how the conversion between Go language structure and binary array is. The content is concise and easy to understand, which will definitely brighten your eyes. I hope you can get something through the detailed introduction of this article.

Go language structure and binary array conversion

The transmission of the structure as a binary stream is a function that is often used as a protocol. To convert a structure to a byte array, you only need to cast a pointer type in the C language. There are pointers in the Go language, but they are not as free as pointers in C, and any type of conversion cannot be done by default. The Go language provides a more secure way. The simplest and most efficient way is to use the Gob library. Alternatively, you can use encoding/binary to convert byte strings into structures. Here is an example of how to use it: a video tutorial

Package mainimport ("fmt"bytes"encoding/binary") func main () {buf: = new (bytes.Buffer) var data = [] interface {} {uint16 (61374), int8 (- 54), uint8 (254th),} 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 ())}

Convert with a pointer

Of course, structures and strings have the same memory structure and can also be converted to pointers, although this is wrong with the capacity.

Package mainimport ("unsafe"; "fmt") func main () {var a uint = 0xbeefcafe fmt.Println (* (* byte) (unsafe.Pointer (& a)} the above is what the conversion between Go language structure and binary array is like. Have you learned any knowledge or skills? If you want to learn more skills or enrich your knowledge reserve, you are welcome to follow the industry information channel.

Tags: Structure language binary array pointer content byte skill knowledge type valid concise secure free concise example memory function character string Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Huawei Redmi Shulou Tech Info vpn OPPO Reno