Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to convert Golang string to byte array

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

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!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report