Get the App
SLTechnology News&Howtos  ›  Development  › 

How to convert Golang string to byte array

Shulou Source: shulou.com Published: 2022-06-01 13:11:48 09月30日 Update

This article focuses on "how to convert Golang strings and byte arrays". Interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Now let the editor take you to learn how to convert Golang strings to byte arrays.

String and byte array?

String is one of the most commonly used basic data types in Go language. it is essentially a read-only character array. Although strings are often regarded as a whole, strings are actually a continuous memory space.

Another type byte (Byte) in Go language. In ASCII, an English letter occupies one byte of space and a Chinese character occupies two bytes of space. English punctuation accounts for one byte and Chinese punctuation accounts for two bytes. The elements in an Byte array correspond to an ASCII code.

Second, detailed code 1. Byte to string

The code is as follows (example):

Func BytesToString (data [] byte) string {return * (* string) (unsafe.Pointer (& data)) 2. String to byte array

The code is as follows (example):

Func StringToBytes (data string) [] byte {return * (* [] byte) (unsafe.Pointer (& data))} 3. Run the test completely

The code is as follows (example):

Func BytesToString (data [] byte) string {return * (* string) (unsafe.Pointer (& data))} func StringToBytes (data string) [] byte {return * (* [] byte) (unsafe.Pointer (& data))} func main () {str: = "hello world!" Fmt.Println (str) a: = StringToBytes (str) fmt.Println (a) b: = BytesToString (a) fmt.Println (b)}

Result (example):

Successfully translated Hello world!

At this point, I believe you have a deeper understanding of "how to convert Golang strings and byte arrays". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Tags: Byte character string array code example space two content actual punctuation type language Chinese English learning character type practical deeper successful Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno OPPO Reno Docker MariaDB Redmi NVidia