为什么十六进制数以 0x 为前缀? [英] Why are hexadecimal numbers prefixed with 0x?
问题描述
为什么十六进制数字的前缀为 0x
?我了解前缀的用法,但我不明白为什么选择 0x
的意义.
Why are hexadecimal numbers prefixed as 0x
?
I understand the usage of the prefix but I don't understand the significance of why 0x
was chosen.
推荐答案
Short story: 0
告诉解析器它正在处理一个常量(而不是一个标识符/保留字).仍然需要一些东西来指定基数:x
是一个任意选择.
Short story: The 0
tells the parser it's dealing with a constant (and not an identifier/reserved word). Something is still needed to specify the number base: the x
is an arbitrary choice.
长话:在 60 年代,流行的编程数字系统是十进制和八进制——大型机每字节有 12、24 或 36 位,可以很好地整除3 = log2(8).
Long story: In the 60's, the prevalent programming number systems were decimal and octal — mainframes had 12, 24 or 36 bits per byte, which is nicely divisible by 3 = log2(8).
BCPL 语言使用语法 8 1234
表示八进制数.当 Ken Thompson 从 BCPL 创建 B 时,他使用了 0
前缀.这很棒,因为
The BCPL language used the syntax 8 1234
for octal numbers. When Ken Thompson created B from BCPL, he used the 0
prefix instead. This is great because
- 一个整数常量现在总是由一个标记组成,
- 解析器仍然可以立即判断它有一个常量,
- 解析器可以立即告诉基数(
0
在两个基数中是相同的), - 在数学上是合理的 (
00005 == 05
),并且 - 不需要珍贵的特殊字符(如
#123
).
- an integer constant now always consists of a single token,
- the parser can still tell right away it's got a constant,
- the parser can immediately tell the base (
0
is the same in both bases), - it's mathematically sane (
00005 == 05
), and - no precious special characters are needed (as in
#123
).
当从 B 创建 C 时,出现了对十六进制数的需求(PDP-11 有 16 位字),并且上述所有要点仍然有效.由于其他机器仍然需要八进制,所以任意选择了 0x
(00
可能被排除为笨拙).
When C was created from B, the need for hexadecimal numbers arose (the PDP-11 had 16-bit words) and all of the points above were still valid. Since octals were still needed for other machines, 0x
was arbitrarily chosen (00
was probably ruled out as awkward).
C# 是 C 的后代,所以它继承了语法.
C# is a descendant of C, so it inherits the syntax.
这篇关于为什么十六进制数以 0x 为前缀?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!