带前导零的 int 变量?
为什么下面的结果是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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
但在许多语言中,前导 0 确实表示八进制,就像这里的情况一样。
but a leading 0 does indicate octal in many languages, as is the case here.
它确实与八进制数有关,
042
被解释为八进制数42
,即4 * 8 + 2 = 34
。请注意,在加载 PHP 脚本时解析数字文字时会发生八进制解释。它与
intval()
无关,后者在这里不执行任何操作,因为该值已经是整数。八进制解释仅发生在数字文字上,而不是在将字符串转换为整数时发生:
It does have to do with octal numbers,
042
is interpreted as the octal number42
which is4 * 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:
在 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.
这就是函数的定义方式。前导零是一条指令,将其解析为八进制数,类似于 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.
向此函数传递带有前导“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