golang string与[]byte互

栏目: Go · 发布时间: 7年前

内容简介:string与[]byte经常需要互相转化,普通转化会发生底层数据的复制。如果是临时使用的字符串可以通过unsafe包直接转化数据,不需要内存拷贝这种方法有需要注意的地方,使用转化后的结果时必须要保证原内存还在,临时变量比较合适这种场景,如:byte2int

string与[]byte经常需要互相转化,普通转化会发生底层数据的复制。如果是临时使用的字符串可以通过unsafe包直接转化数据,不需要内存拷贝

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

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

这种方法有需要注意的地方,使用转化后的结果时必须要保证原内存还在,临时变量比较合适这种场景,如:byte2int

func parseIntBytes(b []byte, base int, bitSize int) (i int64, err error) {
    s := unsafeBytesToString(b)
    return strconv.ParseInt(s, base, bitSize)
}

以上所述就是小编给大家介绍的《golang string与[]byte互》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Introduction to Computation and Programming Using Python

Introduction to Computation and Programming Using Python

John V. Guttag / The MIT Press / 2013-7 / USD 25.00

This book introduces students with little or no prior programming experience to the art of computational problem solving using Python and various Python libraries, including PyLab. It provides student......一起来看看 《Introduction to Computation and Programming Using Python》 这本书的介绍吧!

HTML 压缩/解压工具
HTML 压缩/解压工具

在线压缩/解压 HTML 代码

RGB转16进制工具
RGB转16进制工具

RGB HEX 互转工具

HSV CMYK 转换工具
HSV CMYK 转换工具

HSV CMYK互换工具