How to convert string to byte array (byte) in golang

PHPz
Release: 2023-03-22 14:56:48
Original
2399 people have browsed it

Golang is a powerful programming language with many useful libraries and functions. One very useful feature is converting a string into a byte array. In this article, we will take a deep dive into how to convert a string to a byte array using Golang functions.

Golang provides several methods to convert strings to byte arrays. The most commonly used methods are to use the []byte function and []rune function. The two functions are defined as follows:

func []byte(s string) []byte
func []rune(s string) []rune
Copy after login

[]byte function converts a string to a byte array, while []rune function converts a string to Unicode character array. Both functions will return a new byte array or character array containing a copy of the string passed in.

If you want to convert a string to a byte array, you can use the following code:

s := "Hello, World!"
b := []byte(s)
fmt.Printf("%v\n", b)
Copy after login

The output is:

[72 101 108 108 111 44 32 87 111 114 108 100 33]
Copy after login

This code snippet converts the string "Hello , World!" into a byte array and print it out. As can be seen, each character is converted to its ASCII value and stored in a byte array.

If you want to convert a string to a Unicode character array, you can use the following code:

s := "안녕하세요"
r := []rune(s)
fmt.Printf("%v\n", r)
Copy after login

The output result is:

[44032 45208 45796 54620]
Copy after login

This code snippet will convert a Korean string " 안녕하세요" into a character array and print it out. Each character corresponds to a Unicode code value and is stored in a character array.

It should be noted that the []rune function only applies to Unicode characters. If the string only contains ASCII characters, you can use the []byte function.

In general, Golang's string to byte array function is easy to use, flexible and diverse. You can flexibly choose which method to use for conversion based on actual needs. Hope this article helps you!

The above is the detailed content of How to convert string to byte array (byte) in golang. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template