Function pack() returns 0
Why can such code a开发者_StackOverflow社区s pack('i',6)
return 0?
All php.net says about return values of this function:
Returns a binary string containing data.
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.
$ php -r 'var_dump(bin2hex(pack("i",6)));'
string(8) "06000000"
(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 the ACK
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.
If the string starts with valid numeric data, this will be the value used. Otherwise, the value will be 0 (zero).
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.
精彩评论