-6

I have a slice of bytes to represent a null-terminated string with trailing garbage bytes.

I followed How can I convert a zero-terminated byte array to string?

s := string(byteArray[:n])

but it doesn't work

[54 49 0 101 0 0 0 0 64 31 1 0 0]
61e@

instead of just 61

I've also tried to trim the slice: bytes.Trim(buf[:], "\x00") same result.

https://go.dev/play/p/FDPPLgGjHOY

0

1 Answer 1

0

You have to first find where the 0 is:

ix:=bytes.IndexByte(byteArray,0)
if ix==-1 {
  ix=len(byteArray)
}
s:=string(byteArray[:ix])
Sign up to request clarification or add additional context in comments.

3 Comments

I tried to use a method that should do exactly that bytes.Trim(buf[:], "\x00") but it doesn't work.
Trim only removes leading/trailing zeros, in this case, the last two
Too bad there isn't a similar method to trim a slice once a value is found. And what a confusing name bytes.Trim that actually doesn't trim... Thanks! I used your code and it worked.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.