Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

unpacking 4 bytes into a float in PHP

Tags:

php

pack

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.

like image 252
Tac Tacelosky Avatar asked May 23 '26 06:05

Tac Tacelosky


1 Answers

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.

like image 195
Syscall Avatar answered May 24 '26 21:05

Syscall



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!