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.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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,
\0char). Since this byte is used to denote string ends in C and other languages,echoand 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 theACKcharacter. 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
\6char is neither a sign nor a digit (the chars 0-9 are decimal\48–\57or\0x30–\0x39hexadecimal) PHP returns zero.