在 php < 5.6 中模拟 pack('J')

Simulate pack('J') in php < 5.6

我在 php 5.5 中需要 pack('J', $val),但仅在 5.6 及更高版本中支持 'J'。

如何在php-5.5 中模拟它? 64位全部打包,真的没必要。

我的尝试似乎不正确(在 Win7 64 位上):

pack('J', $val) === pack('N', 0) . pack('N', $val)

可能有更聪明的方法来做到这一点,但这个有效:

// base_convert() will treat your value as a string here,
// converting it from decimal to hexadecimal
$hexStringValue = base_convert($your64bitInteger, 10, 16);

// Pad with zeros to the left, until pack()'s output length is matched
$hexStringValue = str_pad($hexStringValue, 16, '0', STR_PAD_LEFT);

// Convert to binary
$packed64bitInteger = hex2bin($hexStringValue);

但是我必须注意,PHP 5.5 reached EOL in July 2016 无论如何您应该至少升级到 5.6 版。