英文:
The difference between "A" and "A"[0]
问题
我为将TEXT
转换为BINARY
编写了以下代码:
fmt.Printf("%s\n", fmt.Sprintf("%08b", "A"))
但是它不起作用,输出的消息是:%!b(string=0000000A)
但是当我将"A"
更改为"A"[0]
时,它正常工作:
fmt.Printf("%s\n", fmt.Sprintf("%08b", "A"[0]))
输出结果是01000001
上述语句之间有什么区别?
英文:
I write this code for convert TEXT
to BINARY
fmt.Printf("%s\n", 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\n", fmt.Sprintf("%08b", "A"[0]))
output is 01000001
what is difference between above statements?
答案1
得分: 4
Golang将字符串与字节区分开来。
"A"
是一个字符串,严格来说是一个只读的字节切片。"A"[0]
是该序列中的第一个字节,其值为0x41。
你要求先打印一个字符串("A"
),然后再打印一个字节("A"[0]
),并使用二进制数字在一个长度为八个字符的字段中显示。你的第一个输出很有趣,因为你试图将一个字符串打印成某种字节值。但是,一个字节序列并不等同于一个单独的字节。你的第二个输出更自然,因为你获取了字符串的第一个字节(索引为0),得到了0x41。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论