Go中的十六进制编码



我想用golang比较两个十六进制字节序列。我是一个初学者,不知道如何从Hex创建字节变量。下面是我尝试做的代码。

import "bytes" 
static-bytes := //Set hex here, something like 504B0506
static-bytes2 := //Set hex here, something like 504B
fmt.Println(bytes.Contains(static-bytes, static-bytes2))

如果您的输入是十六进制字符串,您可以使用encoding/hex包,特别是DecodeString,将字符串转换为字节。例如:

b1, _ := hex.DecodeString("737461636b6f766572666c6f77")

或者,如果你使用的是@Adrian提到的十六进制记数法中的整数文字,你可以使用以下内容:

b2 := []byte{ 0x6f, 0x76, 0x65, 0x72, 0x66, 0x6c, 0x6f, 0x77 }

这将使您能够按预期比较序列:

b1, _ := hex.DecodeString("737461636b6f766572666c6f77")
b2 := []byte{ 0x6f, 0x76, 0x65, 0x72, 0x66, 0x6c, 0x6f, 0x77}
println(bytes.Contains(b1, b2))

最新更新