string from byte[] buffer?

3,039 views
Skip to first unread message

Leon

unread,
Apr 6, 2011, 5:18:53 AM4/6/11
to golang-nuts
Hello there,

I'm fairly new to go and I've got a little problem with byte buffers
representing NULL-terminated C-strings and Go strings. (I googled but
googling for 'go + <keyword>' seems rather unproductive).

So, I'm reading a buffer of bytes from a net.Conn and would like to
convert the byte buffer into a "real" string (to do further string
processing). Given the simplified code:

var buf [512]byte
n, err := conn.Read(buf[0:])
s := string(buf[:])

's' seems to be a string but when I run a len(s) it does return the
length of buf instead of the string's length. Printing out the
contents of the string it seems to contain a bunch of \0.

Now I look for the right solution to get a string without \0 from the
byte buffer. I came up with:

s := string(buf[0:n])

Which will give me a string of the "proper" length which I can trim
properly. But I don't know if this is the right way to do it.

So my questions:

1) What is the right way to get a string from a []byte representing a
NULL-terminated string?
2) Is it legal for go strings to contain \000 bytes? (I guess it is)


regards,
Leon

roger peppe

unread,
Apr 6, 2011, 5:36:44 AM4/6/11
to Leon, golang-nuts
On 6 April 2011 10:18, Leon <leon.sz...@googlemail.com> wrote:
> Now I look for the right solution to get a string without \0 from the
> byte buffer. I came up with:
>
>    s := string(buf[0:n])
>
> Which will give me a string of the "proper" length which I can trim
> properly. But I don't know if this is the right way to do it.

that's exactly the right way to do it.

alternatively, you don't necessarily have to convert to string
at all - you could just trim the byte slice in place
(the bytes package has all the usual string manipulation functions
that work on []byte instead of string).

>
> So my questions:
>
> 1) What is the right way to get a string from a []byte representing a
> NULL-terminated string?

there are no NULL-terminated strings in Go unless you're calling
C or reading from something external that provides such a string.

> 2) Is it legal for go strings to contain \000 bytes? (I guess it is)

go strings are just immutable byte arrays - it's only
convention that they hold utf-8 encoded text
(apart from the fact that range on a string ranges over
code points, not bytes)

thus there's no problem with them holding 0 bytes.

Reply all
Reply to author
Forward
0 new messages