18

how would I convert an integer to an array of 4 bytes?

Here is the exact code I want to port (in C#)

int i = 123456;
byte[] ar = BitConverter.GetBytes(i);
// ar will contain {64, 226, 1, 0}

How would I do the exact same thing in PHP ?

1
  • 1
    Are you looking for the result to be an array containing the decimal numbers 64, 226 etc? Or are you actually looking for the bytes, which in PHP would be a string? Commented Jul 18, 2012 at 15:36

2 Answers 2

23

The equivalent conversion is

$i = 123456;
$ar = unpack("C*", pack("L", $i));

See it in action.

You should be aware though that the byte order (little/big endian) is dependent on the machine architecture (as it is also in the case of BitConverter). That might or might not be good.

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

Comments

7

Since the equivalent of a byte array in PHP is a string, this'll do:

$bytes = pack('L', 123456);

To visualize that, use bin2hex:

echo bin2hex($bytes);
// 40e20100
// (meaning 64, 226, 1, 0)

4 Comments

Might be true. But I still needed the single bytes in a array. Thanks anyway.
@user echo $bytes[0], $byte[1], $byte[2], $byte[3]; PHP strings are in essence byte arrays.
Oh, ok! Excuse my ignorance then. Now that you mention it, I think that I might be overcomplicating things A LOT in PHP...
@user1392060 If you want single bytes in an array you could try str_split($bytes).

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.