1锤岸、golang中hex包是什么?
2板乙、hex包給開發(fā)者提供了什么內(nèi)容?以及怎么使用拳氢?
3募逞、相關(guān)鏈接
一、golang中hex包是什么馋评?
hex包實(shí)現(xiàn)了16進(jìn)制字符表示的編解碼放接。
二、hex包給開發(fā)者提供了什么內(nèi)容留特?以及怎么使用纠脾?
變量
var ErrLength = errors.new("encoding/hex: odd length hex string")
解碼一個長度為奇數(shù)的切片時,將返回此錯誤
type InvalidByteError byte
描述一個hex編碼字符串中的非法字符蜕青。
func (e InvalidByteError) Error() string
函數(shù)
1)func DecodeLen(x int) int
長度x的編碼數(shù)據(jù)解碼后的明文數(shù)據(jù)的長度
2)func Decode(dst, src []byte) (int, error)
將src進(jìn)行解碼苟蹈,返回實(shí)際寫入dst的字節(jié)數(shù),如果產(chǎn)生錯誤右核,返回描述錯誤的error慧脱。
3)func DecodeString(s string) ([]byte, error)
返會解碼后的數(shù)據(jù),以及可能會產(chǎn)生的錯誤贺喝。
4)func EncodedLen(n int) int
長度x的明文數(shù)據(jù)編碼后的編碼數(shù)據(jù)的長度菱鸥。
5)func Encode(dst, src []byte) int
將src的數(shù)據(jù)解碼為EncodedLen(len(src))字節(jié)宗兼,返回實(shí)際寫入dst的字節(jié)數(shù):EncodedLen(len(src))。
6)func EncodeToString(src []byte) string
將數(shù)據(jù)src編碼為字符串s
7)func Dump(data []byte) string
返回給定數(shù)據(jù)的hex dump格式的字符串氮采,這個字符串與控制臺下下 hexdump -C
對該數(shù)據(jù)的輸出是一致的殷绍。
8)func Dumper(w io.Writer) io.WriteCloser
返回一個io.WriteCloser接口,將寫入的數(shù)據(jù)的hex dump格式寫入w鹊漠,具體格式為hexdump -C
代碼案例
package main
import (
"encoding/hex"
"fmt"
"github.com/lunny/log"
"os"
)
func main() {
// 編碼
src := []byte("hello")
maxEnLen := hex.EncodedLen(len(src)) // 最大編碼長度
dst1 := make([]byte, maxEnLen)
n := hex.Encode(dst1, src)
dst2 := hex.EncodeToString(src)
fmt.Println("編碼后的結(jié)果:", string(dst1[:n]))
fmt.Println("編碼后的結(jié)果:", dst2)
// 解碼
src = dst1
maxDeLen := hex.DecodedLen(len(src))
dst1 = make([]byte, maxDeLen)
n, err := hex.Decode(dst1, src)
if err != nil {
log.Println(err)
} else {
fmt.Printf("%s解碼后的數(shù)據(jù)為:%s\n", src, string(dst1[:n]))
}
dst3, err := hex.DecodeString(string(src))
fmt.Printf("%s解碼后的數(shù)據(jù)為:%s\n", src, string(dst3[:n]))
// dump
fmt.Printf(hex.Dump(src))
// dumper
stdoutDumper := hex.Dumper(os.Stdout)
defer stdoutDumper.Close()
stdoutDumper.Write(src)
}
/*
輸出內(nèi)容:
編碼后的結(jié)果: 68656c6c6f
編碼后的結(jié)果: 68656c6c6f
68656c6c6f解碼后的數(shù)據(jù)為:hello
68656c6c6f解碼后的數(shù)據(jù)為:hello
00000000 36 38 36 35 36 63 36 63 36 66 |68656c6c6f|
00000000 36 38 36 35 36 63 36 63 36 66
*/
三主到、相關(guān)鏈接
1、https://studygolang.com/pkgdoc