First let’s consider how to convert a byte to a string? Simple, the language specification tells us, just do it like string(the_byte)
. But there is a secret here, see the following code:
Guess what you get? The result is:
Suprizing, huh! The result for 0x80
is c280
! If you change the modifier in fmt from %x
to %q
, you can see more clearly:
When converting a byte to a string using string(the_byte)
, the result is an encoded one. So you get "\u0080"
from string(0x80)
. It applies to not only byte, but all integer types.
This isn’t the case we see in C or C++. So, how do we get string "\0x80"
form byte 0x80
. You will have to do it with byte slice:
Another way to do is using bytes.Buffer
:
bytes.Buffer
is very efficient, according to the benchmark, it is the faster way to concatenate a string, better than slice appending and operator ‘+’.