TOC

Golang Bytes 相关操作

byte 实际上是 uint8 的别名,[]byte 也就是 uint8 切片。

常见操作

package main

import (
    "bytes"
    "encoding/hex"
    "fmt"
    "strconv"
)

func main() {
    // 1. 转换
    str1 := "HELLO WORLD"
    bytes0 := []byte(str1) // string to bytes
    str2 := string(bytes0) // bytes to string
    fmt.Printf("%#v\n", bytes0)
    // []byte{0x48, 0x45, 0x4c, 0x4c, 0x4f, 0x20, 0x57, 0x4f, 0x52, 0x4c, 0x44}
    fmt.Println(str1, bytes0, str2)
    // HELLO WORLD [72 69 76 76 79 32 87 79 82 76 68] HELLO WORLD

    // 2. 连接
    bytes1 := []byte("HELLO ")
    bytes2 := []byte("WORLD")
    bytes3 := append(bytes1, bytes2...)
    fmt.Println(bytes3)
    // [72 69 76 76 79 32 87 79 82 76 68]

    // 3. 拷贝
    bytes4 := make([]byte, len(bytes3))
    copy(bytes4, bytes3)
    fmt.Println(bytes4)
    // [72 69 76 76 79 32 87 79 82 76 68]

    // 4. 长度和容量
    fmt.Println(len(bytes4), cap(bytes4)) // 11 11

    // 5. 截取
    bytes5 := bytes4[7:10]
    fmt.Println(bytes5) // [79 82 76]

    // 6. 比较
    bytes6 := []byte("HELLO WORLD")
    fmt.Println(bytes.Equal(bytes4, bytes6)) // true

    // 7. 遍历
    for i := 0; i < len(bytes6); i++ {
        fmt.Printf("%d ", bytes6[i])
    }
    fmt.Println()
    // 72 69 76 76 79 32 87 79 82 76 68

    // 8. 转化为数字
    bytes7 := []byte("12345")
    num, _ := strconv.Atoi(string(bytes7))
    fmt.Println(num) // 12345

    // 9. 转化为16进制字符串
    bytes8 := []byte("HELLO WORLD")
    hexStr := hex.EncodeToString(bytes8)
    fmt.Println(hexStr) // 48454c4c4f20574f524c44
}

输出

package main

import (
    "bytes"
    "fmt"
    "io"
    "os"
)

func main() {
    buf := new(bytes.Buffer) // *bytes.Buffer
    // func (b *Buffer) WriteString(s string) (n int, err error)
    buf.WriteString("HELLO ")
    buf.WriteString("WORLD")

    fmt.Println(string(buf.Bytes()))
    fmt.Println(buf.String()) // 相同

    // ========================================

    w := os.Stdout // *os.File
    // func (f *File) Write(b []byte) (n int, err error)
    // func (f *File) WriteString(s string) (n int, err error)
    w.WriteString("HELLO ")

    n, err := io.WriteString(w, "WORLD\n")
    if err != nil {
        panic(err)
    }
    fmt.Printf("n: %d\n", n)
}

利用 reflect 实现 bytes / string 转换

参考:https://www.sobyte.net/post/2022-01/go-string-bytes/

func String2Bytes(s string) []byte {
    sh := (*reflect.StringHeader)(unsafe.Pointer(&s))
    bh := reflect.SliceHeader{
        Data: sh.Data,
        Len:  sh.Len,
        Cap:  sh.Len,
    }
    return *(*[]byte)(unsafe.Pointer(&bh))
}

func Bytes2String(b []byte) string {
    return *(*string)(unsafe.Pointer(&b))
}