Estou trabalhando em um código onde sei a posição inicial de uma string em um pacote, e sei o terminador da string, que é 0x00 0x00 0x00. Preciso substituir a string antiga por uma nova, mas estou tendo um problema: a nova string pode ser maior ou menor que a antiga, e não posso interferir nos outros bytes do meu pacote. Alguém pode me ajudar com isso?
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)
}
Aqui está uma solução que retorna um
[]byte
, ou umerror
. Ele é projetado para tolerar NULs UTF-16 simples antes do terminador. Ele requer Go1.21
paraslices.Replace
.