一些关于.class文件开头魔数的轶事

在编程过程中,我们可能经常听到“魔数”这个词,那么这个词到底指的是什么呢?什么数叫做魔数呢?

大多数情况下,我们都是通过扩展名来识别一个文件的类型的,比如我们看到一个.txt类型的文件我们就知道他是一个纯文本文件。但是,扩展名是可以修改的,那一旦一个文件的扩展名被修改过,那么怎么识别一个文件的类型呢。这就用到了我们提到的“魔数”。

很多类型的文件,其起始的几个字节的内容是固定的(或是有意填充,或是本就如此)。因此这几个字节的内容也被称为魔数 (magic number),因为根据这几个字节的内容就可以确定文件类型。有了这些魔术数字,我们就可以很方便的区别不同的文件。

为了方便虚拟机识别一个文件是否是class类型的文件,SUN公司规定每个class文件都必须以一个word(四个字节)作为开始,这个数字就是魔数。魔数是由四个字节的无符号数组成的,而class文件的名字还挺好听的的,其魔数就是0xCAFEBABE

读者可以随便编译一个class文件,然后然后用十六进制编辑器打开编译后的class文件,基本格式如下:
在这里插入图片描述
为什么java的魔数是cafebabe?

James Gosling曾解释过这件事情:

As far as I know, I’m the guilty party on this one. I was totally unaware of the NeXT connection. The small number of interesting HEX words is probably the source of the match. As for the derivation of the use of CAFEBABE in Java, it’s somewhat circuitous:
We used to go to lunch at a place called St Michael’s Alley. According to local legend, in the deep dark past, the Grateful Dead used to perform there before they made it big. It was a pretty funky place that was definitely a Grateful Dead Kinda Place. When Jerry died, they even put up a little Buddhist-esque shrine. When we used to go there, we referred to the place as Cafe Dead.
Somewhere along the line it was noticed that this was a HEX number. I was re-vamping some file format code and needed a couple of magic numbers: one for the persistent object file, and one for classes. I used CAFEDEAD for the object file format, and in grepping for 4 character hex words that fit after CAFE (it seemed to be a good theme) I hit on BABE and decided to use it.
At that time, it didn’t seem terribly important or destined to go anywhere but the trash-can of history. So CAFEBABE became the class file format, and CAFEDEAD was the persistent object format. But the persistent object facility went away, and along with it went the use of CAFEDEAD - it was eventually replaced by RMI.

可以看到他表示这么几个意思,首先他经常去一家咖啡馆,这家咖啡馆在当地被称为死亡咖啡馆CAFEDEAD,这几个字都恰好可以用十六进制表示,于是他用这个来表示对象格式,进而想到用CAFEBABE表示类文件格式,于是得到了延续。

原创文章 46 获赞 7 访问量 2092

猜你喜欢

转载自blog.csdn.net/EdwardWH/article/details/105003647
今日推荐