Search code examples
phppack

unpacking 4 bytes into a float in PHP


I'm stuck on how to reverse a process. This part works:

$ar = unpack("C*", pack("f", -4));

array:4 [▼
  1 => 0
  2 => 0
  3 => 128
  4 => 192
]

# in hex
array:4 [▼
  1 => "00"
  2 => "00"
  3 => "80"
  4 => "c0"
]

Now I want to do the reverse: I have a hex string '000080c0' and I want to unpack it into a float and have the result be -4. How do I do that in PHP?

Thanks.


Solution

  • You can split the string in groups of 2 hex characters (1 byte), and convert them in decimal values.

    Then, you just need to unpack/pack to get the final float.

    To use pack(), you could use the splat operator (...) to unpack values of the array in function's parameters.

    $src = '000080c0';
    
    // get ['00','00','80','C0']
    $arr = array_map('hexdec', str_split($src, 2));
    
    // pack as bytes, unpack as float
    $float = unpack('f', pack("C*", ...$arr));
    
    var_dump($float[1]); // float(-4)
    

    See a working example.