函数 pack() 返回 0
为什么pack('i',6)
这样的代码会返回0?
所有 php.net 都提到了该函数的返回值:
返回一个二进制字符串,其中包含 数据。
Why can such code as pack('i',6)
return 0?
All php.net says about return values of this function:
Returns a binary string containing
data.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你必须在这里说得更具体一些。返回类型是什么?它是一个二进制字符串,因此通常您看到的并不是它实际包含的内容。
它可以以一些空字节开始(即 value=0,
\0
char)。由于该字节在 C 和其他语言中用于表示字符串结尾,因此echo
和其他函数在遇到空字节时会停止(有时手册中会说函数是“二进制安全”的,这意味着它不将空字节视为字符串结尾)。还有很多不可打印的字符。它们通常具有某种特殊含义(例如,字符 7 是“bell”命令,请在 shell 中输入此命令来尝试
php -r 'echo "\7";'
)。要找出字符串中的内容,您可以将每个字符“转换”为其十六进制表示形式。您可以使用
bin2hex()
为此,请注意它需要两个字符来表示输入字符串的一个字符。(您在上面看到的输出取决于您的硬件。)在我的例子中
pack('i', 6);
返回 little-endian 格式,因为我有一个英特尔处理器。您可以看到第一个字符 (
06
) 的十进制值为 6。然后您通常要做的就是查找该字符属于哪个字符。在许多情况下,可以使用 ASCII 表,但请注意,如果您使用 unicode 或任何其他编码,某些字符可能有其他含义。根据我的 ASCII 表,它是ACK
字符。它是一个不可打印的字符,仅具有控制功能。仍然需要解释的是为什么这会转换为整数 0。幸运的是这非常简单。阅读 PHP 手册页,了解 将字符串转换为数字。
由于
\6
字符既不是符号也不是数字(字符 0-9 是十进制\48
-\57
或\0x30
-\0x39
十六进制)PHP 返回零。You have to be a bit more specific here. What's the return type? It's a binary string, so often what you see is not what it actually contains.
It could start with a few null bytes (i.e. value=0,
\0
char). Since this byte is used to denote string ends in C and other languages,echo
and other functions stop when they encounter a null byte (sometimes the manual says a function is 'binary-safe', which means it does not consider a null byte as string end).Also there are a lot of non-printable characters. They usually have some kind of special meaning (for example character 7 is the "bell" command, type this into your shell to try it out
php -r 'echo "\7";'
).To find out what's in your string, you could "convert" each char to its hexadecimal representation. You can use
bin2hex()
for this, note that it needs two chars to represent one char of the input string.(The output you see above depends on your hardware.) In my case
pack('i', 6);
returns the integer in little-endian format, since I've got an Intel processor.You can see that the first char (
06
) has the decimal value 6. What you then do is usually look up which character this belongs to. In many cases it's okay to use an ASCII table, but note that in case you're using unicode or any other encoding certain characters could have another meaning. According to my ASCII table, it's theACK
character. It's a non-printable character, it has control function only.What remains to be explained is why this translates to integer 0. Fortunately that's very easy. Read the PHP manual page on casting strings to numbers.
Since the
\6
char is neither a sign nor a digit (the chars 0-9 are decimal\48
-\57
or\0x30
-\0x39
hexadecimal) PHP returns zero.