本文主要是介绍encoding/hex,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
hex 实现了16进制字符表示编解码
func Encode(dst,src []byte)int
func EncodeToString(src []byte)string
func Decode(dst,src []byte)(int,error)
func DecodeString(src []byte)(string,error)
func DecodedLen(x int) int
func EncodedLen(n int) int
func Dump(data []byte) string
func Dumper(w io.Writer) io.WriteCloser
编码过程
package mainimport ("encoding/hex""fmt"
)func main() {str := []byte("12345678")n := hex.EncodedLen(len(str))dst := make([]byte,n)// 方式1 编码字符hex.Encode(dst,str)fmt.Println(dst)fmt.Println(string(dst))// 方式 2 编码为字符串fmt.Println(hex.EncodeToString(str))
}

解码过程
package mainimport ("encoding/hex""fmt"
)func main() {str := []byte("3132333435363738")n := hex.DecodedLen(len(str))dst := make([]byte,n)// 方式1 编码字符hex.Decode(dst,str)fmt.Println(dst)fmt.Println(string(dst))// 方式 2 编码为字符串data,error := hex.DecodeString(string(str))if error != nil{fmt.Println(error)}fmt.Println(string(data))
}

我们把字符串3132333435363738 解码后 得到原始数据 12345678
hex dump格式的字符串
import ("encoding/hex""fmt"
)func main() {str := []byte("12345678")fmt.Println(hex.Dump(str))
}

格式化hex dump,写入文件
package mainimport ("encoding/hex""os"
)func main() {str := []byte("12345678")fileHex,_:= os.Create("/Users/xujie/go/src/awesomeProject/main/hex.txt")defer fileHex.Close()ioWriter := hex.Dumper(fileHex)ioWriter.Write(str)
}

这篇关于encoding/hex的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!