du1913 2018-02-16 18:48
浏览 52
已采纳

固定字节切片到字符串的转换-忽略null

Is there is efficient way to convert a fixed byte slice to a string without adding null characters to the string?

The traditional way to convert a string from a byte slice is the following:

out := string(b[STRIDX:STRIDX+STRLEN]) 

While this returns a string, the length is always equal to the byte slice length. So while the string looks normal on a Print statement it is still referencing potentiality null values.This has some very odd effects if you append characters to this string.

Right now i scan the byte slice for nulls to limit the byte slice i feed to string. Not very pretty or efficient.

Example: https://play.golang.org/p/hOoaqCOoFl0

  • 写回答

1条回答 默认 最新

  • dongmingxiang0312 2018-02-16 20:43
    关注

    Write a simple function:

    func CToGoString(b []byte) string {
        i := bytes.IndexByte(b, 0)
        if i < 0 {
            i = len(b)
        }
        return string(b[:i])
    }
    

    For your example,

    package main
    
    import (
        "bytes"
        "fmt"
    )
    
    func CToGoString(b []byte) string {
        i := bytes.IndexByte(b, 0)
        if i < 0 {
            i = len(b)
        }
        return string(b[:i])
    }
    
    const (
        BUFLEN = 50
        STRLEN = 10
        STRIDX = 10
    )
    
    func main() {
        test := "test"
        b := [BUFLEN]byte{}
        fmt.Printf("Original
    \tString: '%+v' with length '%d'
    ", test, len(test))
    
        copy(b[10:], []byte(test))
    
        s := CToGoString(b[STRIDX : STRIDX+STRLEN])
        fmt.Printf("Unpacking with []byte()
    \tString: '%+v' with length '%d' Buf:%+v
    ", s, len(s), []byte(s))
    }
    

    Playground: https://play.golang.org/p/mH3CBdM6eG_l

    Output:

    Original
        String: 'test' with length '4'
    Unpacking with []byte()
        String: 'test' with length '4' Buf:[116 101 115 116]
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料