//字符串字节互转
func string2bytes(s string) []byte {
    stringHeader := (*reflect.StringHeader)(unsafe.Pointer(&s))
    bh := reflect.SliceHeader{
       Data: stringHeader.Data,
       Len:  stringHeader.Len,
       Cap:  stringHeader.Len,
    }
    return *(*[]byte)(unsafe.Pointer(&bh))
}
func bytes2string(b []byte) string {
    sliceHeader := (*reflect.SliceHeader)(unsafe.Pointer(&b))
    sh := reflect.StringHeader{
       Data: sliceHeader.Data,
       Len:  sliceHeader.Len,
    }
    return *(*string)(unsafe.Pointer(&sh))
}

func string2bytes1(s string) []byte {
    return *(*[]byte)(unsafe.Pointer(&s))
}

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

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注

Captcha Code