在 PHP 中的 64 位架构上打包/解包 64 位 int [英] Pack / unpack a 64-bit int on 64-bit architecture in PHP

查看:43
本文介绍了在 PHP 中的 64 位架构上打包/解包 64 位 int的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么我在 x64 架构上得到以下输出?

Why do I get the following output on an x64 architecture?

$ php -r 'echo pow(2, 33) . "
";print_r(unpack("Ivalue", pack("I", pow(2, 33))));'
8589934592
Array
(
    [value] => 0
)

它似乎可以处理有符号的 64 位整数,但它不能打包/解包它们.根据文档,http://us3.php.net/pack,我应该的大小依赖于机器,在这种情况下是 64 位.

It seems as though it can handle signed 64-bit ints, but it can't pack / unpack them. According to the documentation, http://us3.php.net/pack, the size of I should be machine-dependent, which in this case is 64 bit.

$ php -r 'echo PHP_INT_MAX;'
9223372036854775807

$ php -v
PHP 5.2.9 (cli) (built: Apr 17 2009 03:29:14)
Copyright (c) 1997-2009 The PHP Group
Zend Engine v2.2.0, Copyright (c) 1998-2009 Zend Technologies

推荐答案

这是一个将任意大小的整数值打包成 N 位的函数:

Here is a function to pack an integer value of any size into N bits:

function encode_int($in, $pad_to_bits=64, $little_endian=true) {
    $in = decbin($in);
    $in = str_pad($in, $pad_to_bits, '0', STR_PAD_LEFT);
    $out = '';
    for ($i = 0, $len = strlen($in); $i < $len; $i += 8) {
        $out .= chr(bindec(substr($in,$i,8)));
    }
    if($little_endian) $out = strrev($out);
    return $out;
}

这是一个解码压缩整数的函数:

Here is a function to decode the packed integers:

    function decode_int(&$data, $bits=false) {
            if ($bits === false) $bits = strlen($data) * 8;
            if($bits <= 0 ) return false;
            switch($bits) {
                    case 8:
                            $return = unpack('C',$data);
                            $return = $return[1];
                    break;

                    case 16:
                            $return = unpack('v',$data);
                            $return = $return[1];
                    break;

                    case 24:
                            $return = unpack('ca/ab/cc', $data);
                            $return = $return['a'] + ($return['b'] << 8) + ($return['c'] << 16);
                    break;

                    case 32:
                            $return = unpack('V', $data);
                            $return = $return[1];
                    break;

                    case 48:
                            $return = unpack('va/vb/vc', $data);
                            $return = $return['a'] + ($return['b'] << 16) + ($return['c'] << 32);
                    break;

                    case 64:
                            $return = unpack('Va/Vb', $data);
                            $return = $return['a'] + ($return['b'] << 32);
                    break;

            }
            return $return;
    }

这篇关于在 PHP 中的 64 位架构上打包/解包 64 位 int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆