0
0
GoHow-ToBeginner · 2 min read

Go: How to Convert Byte to String Easily

In Go, you can convert a byte slice to a string by using string(yourByteSlice). For a single byte, use string(yourByte) to get its string representation.
📋

Examples

Input[72, 101, 108, 108, 111]
OutputHello
Input[65]
OutputA
Input[]byte{}
Output
🧠

How to Think About It

To convert bytes to a string in Go, think of bytes as small pieces of text data. You just need to tell Go to treat those bytes as characters by wrapping the byte or byte slice with string(). This creates a new string from the bytes.
📐

Algorithm

1
Get the byte or byte slice input.
2
Use the <code>string()</code> conversion function on the byte or byte slice.
3
Return or print the resulting string.
💻

Code

go
package main
import "fmt"
func main() {
    b := []byte{72, 101, 108, 108, 111}
    s := string(b)
    fmt.Println(s)

    singleByte := byte(65)
    singleChar := string(singleByte)
    fmt.Println(singleChar)
}
Output
Hello A
🔍

Dry Run

Let's trace converting the byte slice [72, 101, 108, 108, 111] to string.

1

Start with byte slice

b = [72, 101, 108, 108, 111]

2

Convert byte slice to string

s = string(b) which becomes "Hello"

3

Print the string

Output: Hello

StepValue
b[72 101 108 108 111]
s"Hello"
💡

Why This Works

Step 1: Bytes represent characters

Each byte holds a number that corresponds to a character in ASCII or UTF-8 encoding.

Step 2: string() converts bytes to string

Using string() tells Go to read the bytes as characters and build a string.

Step 3: Works for single byte or byte slices

You can convert one byte or many bytes at once using the same string() conversion.

🔄

Alternative Approaches

Using bytes.Buffer
go
package main
import (
    "bytes"
    "fmt"
)
func main() {
    b := []byte{72, 101, 108, 108, 111}
    var buffer bytes.Buffer
    buffer.Write(b)
    fmt.Println(buffer.String())
}
More verbose but useful when building strings incrementally.
Using string concatenation in loop
go
package main
import "fmt"
func main() {
    b := []byte{72, 101, 108, 108, 111}
    s := ""
    for _, c := range b {
        s += string(c)
    }
    fmt.Println(s)
}
Less efficient, but shows manual conversion of each byte.

Complexity: O(n) time, O(n) space

Time Complexity

Converting a byte slice to string takes time proportional to the number of bytes, so O(n).

Space Complexity

A new string is created, so space used is also O(n) for n bytes.

Which Approach is Fastest?

Direct conversion with string() is fastest and simplest compared to building strings manually.

ApproachTimeSpaceBest For
string() conversionO(n)O(n)Simple and fast conversion
bytes.BufferO(n)O(n)Building strings incrementally
Loop concatenationO(n²)O(n)Manual conversion, less efficient
💡
Use string(yourByteSlice) to quickly convert bytes to string in Go.
⚠️
Trying to print a byte slice directly without conversion prints the byte values, not the string.