On a 64-bit server, the representation of the PHP long integer

Source: Internet
Author: User
Tags integer pack readable strlen unpack

In PHP, the conversion of data types can be done directly using the pack. For example, the character type, short integer, integral type, long integer can be used respectively, the parameters C, s, I, N to express, of course, the converted data here is binary data, is not readable, in order to be able to read normally, Direct unpack can be used to make data from the binary stream into a readable character type.
The following are the actual lengths of each type.

$uid = 1346563572;

Length 10, calculated directly for character type

echo strlen ($UID); 10

Convert the short integer, the length is 2, of course, this is more than the short integer value range, so high data will be lost

echo strlen (Pack (' s ', $uid)); 2

Convert to integral type with length 4

echo strlen (Pack (' I ', $uid)); 4

Convert growth integral type, length 4

echo strlen (Pack (' N ', $uid)); 4

Other types are correct, but the long integer on the 64bit machine always represents 4 bits, should be 8bit only, so in order to solve this problem, in the data can not be lost, the following ways to convert.

$i = 333333333333333333;
$v = Pack ("NN", $i >>, $i &0xffffffff);
File_put_contents ("/tmp/long.txt", $v);
echo strlen ($v)

Length of 8

Read can be used in the following ways

$v = file_get_contents ("/tmp/long.txt");
List ($hi, $lo) = Array_values (Unpack ("n*n*", $v));
if ($hi <0) $hi + = (1 < < 32);
if ($ho <0) $lo + + (1 << 32);
Echo ($hi <<) + $lo;

Note: The above scripts are run in a 64-bit version of PHP.




Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.