美文网首页
golang自带hex包的使用说明

golang自带hex包的使用说明

作者: 百里江山 | 来源:发表于2020-02-13 23:02 被阅读0次

hex包主要是将字节流转换成16进制的操作.

主要操作函数

  1. hex.EncodedLen 计算编码的长度, 实际长度*2
  2. hex.DecodedLen 计算解码的长度.实际是长度/2
  3. hex.Encode 编码函数
  4. hex.Decode 解码函数
//16进制解码
func HexDecode(s string) []byte {
    dst := make([]byte, hex.DecodedLen(len(s))) //申请一个切片, 指明大小. 必须使用hex.DecodedLen
    n, err := hex.Decode(dst,  []byte(s))//进制转换, src->dst
    if err != nil {
        log.Fatal(err)
        return nil
    }
    return dst[:n] //返回0:n的数据.
}
//字符串转为16进制
func HexEncode(s string) []byte {
    dst := make([]byte, hex.EncodedLen(len(s))) //申请一个切片, 指明大小. 必须使用hex.EncodedLen
    n := hex.Encode(dst, []byte(s)) //字节流转化成16进制
    return dst[:n]
}

func main() {
    s16 := "6769746875622e636f6d2f79657a696861636b"
    fmt.Println(string(HexDecode(s16)))

    s := "github.com/yezihack"
    fmt.Println(string(HexEncode(s)))

    fmt.Println(hex.Dump([]byte(s)))
}

相关文章

网友评论

      本文标题:golang自带hex包的使用说明

      本文链接:https://www.haomeiwen.com/subject/rpsrfhtx.html