// hexTest project main.go
package main
import (
"encoding/hex"
"fmt"
)
func main() {
str := []byte("Hello World")
dstlen := hex.EncodedLen(len(str))
dst := make([]byte, dstlen)
outlen := hex.Encode(dst, str)
fmt.Println("dstlen = ", dstlen, ", outlen = ", outlen)
/*H 的 16 进制为 0x48 ->输出到 []byte 里面对于的为 52 和 58
4 对应 ASCII 码表中的10进制 52
*/
fmt.Println("hex = ", dst)
hex2strlen := hex.DecodedLen(len(dst))
str2 := make([]byte, hex2strlen)
hex.Decode(str2, dst)
fmt.Println("str2 = ", string(str2), ", dst = ", dst)
estring := hex.EncodeToString([]byte(str))
fmt.Println("estring = ", estring)
fmt.Println("estring = ", []byte(estring))
ebyte, err := hex.DecodeString(estring)
if err != nil {
fmt.Println("hex.DecodeString Error! ", err.Error())
} else {
fmt.Println("ebyte = ", string(ebyte))
}
fmt.Println(hex.Dump(ebyte))
}
编译输出:
C:/Go/bin/go.exe build -i [D:/golang/src/hexTest]
成功: 进程退出代码 0.
D:/golang/src/hexTest/hexTest.exe [D:/golang/src/hexTest]
dstlen = 22 , outlen = 22
hex = [52 56 54 53 54 99 54 99 54 102 50 48 53 55 54 102 55 50 54 99 54 52]
str2 = Hello World , dst = [52 56 54 53 54 99 54 99 54 102 50 48 53 55 54 102 55 50 54 99 54 52]
estring = 48656c6c6f20576f726c64
estring = [52 56 54 53 54 99 54 99 54 102 50 48 53 55 54 102 55 50 54 99 54 52]
ebyte = Hello World
00000000 48 65 6c 6c 6f 20 57 6f 72 6c 64 |Hello World|
成功: 进程退出代码 0.