I write this code for convert TEXT
to BINARY
fmt.Printf("%s
", fmt.Sprintf("%08b", "A"))
and not work, print message: %!b(string=0000000A)
but when i changed "A"
to "A"[0]
work fine:
fmt.Printf("%s
", fmt.Sprintf("%08b", "A"[0]))
output is 01000001
what is difference between above statements?
Golang differentiates strings from bytes.
"A"
is a string, technically a read-only slice of bytes. "A"[0]
is the first byte in this sequence, whose value is 0x41.
You asked to print first a string ("A"
), then secondly a byte ("A"[0]
), in a field of eight characters using binary digits. Your first output was funny because you tried to print a string as if it were some kind of byte value. But a sequence of one byte is not the same as a single byte. Your second output was more natural, since you grabbed the first byte of the string (at index 0), obtaining 0x41.