转go里面字符串转成 字节slice, 字节slice转成字符串

Posted oxspirt

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了转go里面字符串转成 字节slice, 字节slice转成字符串相关的知识,希望对你有一定的参考价值。

原文: https://yourbasic.org/golang/convert-string-to-byte-slice/#convert-string-to-bytes

---------------------------------------------------------------------------

yourbasic.org/golang
技术图片

Basics

When you convert between a string and a byte slice (array), you get a brand new slice that contains the same bytes as the string, and vice versa.

  • The conversion doesn’t change the data;
  • the only difference is that strings are immutable, while byte slices can be modified.

If you need to manipulate the characters (runes) of a string, you may want to convert the string to a rune slice instead. See Convert between rune array/slice and string.

Convert string to bytes

When you convert a string to a byte slice, you get a new slice that contains the same bytes as the string.

b := []byte("ABC€")
fmt.Println(b) // [65 66 67 226 130 172]

Note that the character  is encoded in UTF-8 using 3 bytes. See the Go rune articlefor more on UTF-8 encoding of Unicode code points.

Convert bytes to string

When you convert a slice of bytes to a string, you get a new string that contains the same bytes as the slice.

s := string([]byte65, 66, 67, 226, 130, 172)
fmt.Println(s) // ABC€

Performance

These conversions create a new slice or string, and therefore have time complexityproportional to the number of bytes that are processed.

More efficient alternative

In some cases, you might be able to use a string builder, which can concatenate strings without redundant copying:

以上是关于转go里面字符串转成 字节slice, 字节slice转成字符串的主要内容,如果未能解决你的问题,请参考以下文章

go_字符和字符串处理

将字节数组转成易读的字符串

2字节字符串,怎么转成整数

字节数组怎么转string

c++接收数据的时候,需要把网络字节序转成主机字节序吗

java里面byte数组和String字符串怎么转换