3

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.

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.