“A”和”A”[0]之间的区别是什么?

huangapple go评论137阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2017年9月5日 11:17:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/46046506.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定