I am new to go, so lot of confusion regarding bytes concept.
While going through some go code, I came across some thing like
[]byte("\xd2\xfd\x88g\xd5-\xfe")
was it in hexa decimal or bytes format?
what are some chars in above like g,r-,e
signifies?
And how to print it in log?
[]byte("\xd2\xfd\x88g\xd5-\xfe")
is an interpreted string literal converted to type []byte
, a byte
slice. Here it is separated into byte values:
[\xd2, \xfd, \x88, g, \xd5, , -, \xfe]
or, expressed as hexadecimal bytes,
[d2, fd, 88, 67, d5, 0d, 2d, fe]
One way to log the value,
package main
import "log"
func main() {
b := []byte("\xd2\xfd\x88g\xd5-\xfe")
log.Printf("%q
", b)
}
Playground: https://play.golang.org/p/BIh_EuvoxU-
Output:
2009/11/10 23:00:00 "\xd2\xfd\x88g\xd5-\xfe"
A string literal represents a string constant obtained from concatenating a sequence of characters. There are two forms: raw string literals and interpreted string literals.
Raw string literals are character sequences between back quotes, as in
foo
. Within the quotes, any character may appear except back quote. The value of a raw string literal is the string composed of the uninterpreted (implicitly UTF-8-encoded) characters between the quotes; in particular, backslashes have no special meaning and the string may contain newlines. Carriage return characters ('') inside raw string literals are discarded from the raw string value.Interpreted string literals are character sequences between double quotes, as in "bar". Within the quotes, any character may appear except newline and unescaped double quote. The text between the quotes forms the value of the literal, with backslash escapes interpreted as they are in rune literals (except that \' is illegal and \" is legal), with the same restrictions. The three-digit octal ( nn) and two-digit hexadecimal (\xnn) escapes represent individual bytes of the resulting string; all other escapes represent the (possibly multi-byte) UTF-8 encoding of individual characters. Thus inside a string literal \377 and \xFF represent a single byte of value 0xFF=255, while ÿ, \u00FF, \U000000FF and \xc3\xbf represent the two bytes 0xc3 0xbf of the UTF-8 encoding of character U+00FF.
After a backslash, certain single-character escapes represent special values:
\a U+0007 alert or bell \b U+0008 backspace \f U+000C form feed U+000A line feed or newline U+000D carriage return \t U+0009 horizontal tab \v U+000b vertical tab \\ U+005c backslash \' U+0027 single quote (valid escape only within rune literals) \" U+0022 double quote (valid escape only within string literals)