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 关于#java#的问题,请各位专家解答!
  • ¥15 急matlab编程仿真二阶震荡系统
  • ¥20 TEC-9的数据通路实验
  • ¥15 ue5 .3之前好好的现在只要是激活关卡就会崩溃
  • ¥50 MATLAB实现圆柱体容器内球形颗粒堆积
  • ¥15 python如何将动态的多个子列表,拼接后进行集合的交集
  • ¥20 vitis-ai量化基于pytorch框架下的yolov5模型
  • ¥15 如何实现H5在QQ平台上的二次分享卡片效果?
  • ¥30 求解达问题(有红包)
  • ¥15 请解包一个pak文件