Search code examples
phppackphp-5.5

Simulate pack('J') in php < 5.6


I would need pack('J', $val) in php 5.5 but 'J' is supported in 5.6 onwards only.

How can I simulate it in php-5.5? It is not really necessary to pack all 64 bits.

My try does not seem to be correct (on Win7 64bit):

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

Solution

  • There's probably a smarter way to do this, but this works:

    // 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);
    

    I must note however, PHP 5.5 reached EOL in July 2016 and you should be upgrading to at least version 5.6 anyway.