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 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里