带前导零的 int 变量?

发布于 2024-11-15 17:50:12 字数 75 浏览 4 评论 0原文

为什么下面的结果是34? 它似乎与八进制数没有任何关系。

intval(042);

Why is it that following results in 34?
It doesn't seem to have anything to do with octal numbers.

intval(042);

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

|煩躁 2024-11-22 17:50:12

但在许多语言中,前导 0 确实表示八进制,就像这里的情况一样。

but a leading 0 does indicate octal in many languages, as is the case here.

完美的未来在梦里 2024-11-22 17:50:12

它确实与八进制数有关,042 被解释为八进制数 42,即 4 * 8 + 2 = 34

请注意,在加载 PHP 脚本时解析数字文字时会发生八进制解释。它与 intval() 无关,后者在这里不执行任何操作,因为该值已经是整数。

八进制解释仅发生在数字文字上,而不是在将字符串转换为整数时发生:

intval(042)   // == 34
intval('042') // == 42
(int)'042'    // == 42

It does have to do with octal numbers, 042 is interpreted as the octal number 42 which is 4 * 8 + 2 = 34.

Please be aware that the octal interpretation happens when the number literal is parsed while loading the PHP script. It has nothing to do with intval(), which doesn't do anything here because the value is already integer.

Octal interpretation happens only with number literals, not when casting a string to integer:

intval(042)   // == 34
intval('042') // == 42
(int)'042'    // == 42
梅倚清风 2024-11-22 17:50:12

在 PHP 中,以 0 开头的数字被读取为八进制数。

因此 042 被读取为八进制数。

intval()函数将其转换为十进制数,即34。

因此浏览器输出为34。

In PHP a number with leading 0 is read as an octal number.

So 042 is read as an octal number.

The intval() function converts it into decimal number, which is 34.

So the browser output is 34.

揽清风入怀 2024-11-22 17:50:12

这就是函数的定义方式。前导零是一条指令,将其解析为八进制数,类似于 0x 作为前缀表示十六进制。请参阅文档了解更多信息

It's simply how the function is defined. The leading zero is an instruction parse it as an octal number, similarly as to how 0x as a prefix means hex. See the documentation for more information.

糖粟与秋泊 2024-11-22 17:50:12

向此函数传递带有前导“0”的字符串值时要小心。如果您给它“042”,它会将其视为 BASE 8 - 9 并将其转换为十进制值,默认情况下是基数。

请仔细阅读

Be careful when passing this function a string value with a leading "0". If you give it "042" then, it will treat it as BASE 8 - 9 and convert it to decimal value, which is by default base.

Please go through this

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文