我正在编写一些代码,其中我知道数据包中字符串的起始位置,并且知道字符串的终止符,即 0x00 0x00 0x00。我需要用新字符串替换旧字符串,但我遇到了一个问题:新字符串可能比旧字符串大或小,并且我不能干扰数据包中的其他字节。有人能帮我吗?
func replaceString(data []byte, newString string, startPos int) error {
// Checks if the start position is valid
if startPos >= len(data) || startPos < 0 {
return fmt.Errorf("start position out of bounds")
}
terminatorPos := bytes.Index(data[startPos:], []byte{0x00, 0x00, 0x00})
if terminatorPos == -1 {
return fmt.Errorf("termination sequence not found")
}
buf := &bytes.Buffer{}
packets.WriteS(buf, "testing long string")
return nil
}
func WriteS(buf *bytes.Buffer, value string) {
// Converter a string para UCS-2
ucs2 := utf16.Encode([]rune(value))
// Escrever os bytes da string em UCS-2 (little-endian)
for _, char := range ucs2 {
buf.WriteByte(byte(char & 0xff)) // Byte menos significativo
buf.WriteByte(byte((char >> 8) & 0xff)) // Byte mais significativo
}
// Escrever o terminador null (2 bytes de 0x00)
buf.WriteByte(0x00)
buf.WriteByte(0x00)
buf.WriteByte(0x00)
}
这是一个返回修改后的
[]byte
或 的解决方案error
。它被设计为容忍终止符之前的单个 UTF-16 NUL。它需要 Go1.21
来实现slices.Replace
。