SoFunction
Updated on 2025-05-15

Detailed process of converting string and byte slices in Go language

1. String to byte slice: []byte(url)

Conversion principle

Go strings are stored in UTF-8 encoding by default. When executed[]byte(url)When the program converts each character of the string into the corresponding UTF-8 encoded bytes and stores these bytes in a new slice.

Sample code

url := ""
urlBytes := []byte(url)
("Byte slice: %v\n", urlBytes) // Output byte slice(Decimal representation)

flow chart

+-------------------+     +---------------------+     +-------------------+
|   String input       | --> | UTF-8Encoding conversion       | --> | Byte slice output       |
|   (like"example")    |     | (Transfer each character1-4byte) |     | (like[101 120 97...])|
+-------------------+     +---------------------+     +-------------------+

2. The purpose of byte slices

Byte slices are crucial in the following scenarios:

  1. Binary data processing: Network communication, file reading and writing, encryption algorithms, etc.
  2. Interact with the standard library:likeandThe interface processes byte streams.
  3. Performance optimization: Directly operate the byte sequence in memory.

3. Byte slice to string: string(bytes)

passstring()Functions can restore byte slices to strings:

urlStr := string(urlBytes)
("String: %s\n", urlStr) // Output the original string

4. The representation of byte slices

Byte slices are essentially binary data, but can be rendered in different divisions:

1. Binary representation

Each byte is displayed in 8-bit binary:

for _, b := range urlBytes {
    ("%08b ", b) // If 01101000 means the character 'h'}

2. Decimal representation

Convert each byte to an integer of 0-255:

for _, b := range urlBytes {
    ("%d ", b) // If 104 corresponds to 'h'}

3. Hexadecimal representation

Each byte is represented by a two-digit hexadecimal number:

for _, b := range urlBytes {
    ("%02x ", b) // If 68 corresponds to 'h'}

Complete sample code

package main
 
import "fmt"
 
func main() {
    url := "Hello, the world"
    bytes := []byte(url)
  
    ("Binary:")
    for _, b := range bytes { ("%08b ", b) }
  
    ("\nDecimal:")
    for _, b := range bytes { ("%d ", b) }
  
    ("\nHex:")
    for _, b := range bytes { ("%02x ", b) }
}

Output

Binary:
01001000 01100101 01101100 01101100 01101111 00101100 00100000 11100100 10111000 10010110 11100101 10111001 10001010 
Decimal:
72 101 108 108 111 44 32 228 184 150 229 185 138 
Hex:
48 65 6c 6c 6f 2c 20 e4 b8 96 e5 b9 8a 

5. Things to note

  1. Coding consistency: Non-ASCII characters (such as Chinese) may occupy multiple bytes.
  2. Immutability: The string cannot be modified and needs to be operated indirectly through byte slices.
  3. Data replication: The conversion process generates new slices, and large strings may affect performance.

6. Summary

  • []byte(str)Convert the string to byte slices in UTF-8 encoding.
  • string(bytes)Restores the byte slice to a string.
  • Bytes can be represented in binary, decimal or hexadecimal to meet the needs of different scenarios.

Mastering the conversion mechanism of string and byte slices can help developers process text and binary data more flexibly, improving code efficiency and maintainability.

This is the article about the detailed process of string and byte slice conversion in Go language. For more related contents of Go string and byte slice conversion, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!