Take the 2-minute tour ×

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 ?

share|improve this question
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? –  deceze Jul 18 '12 at 15:36
@deceze: byte is an integral type in C#, so I went with the numbers. –  Jon Jul 18 '12 at 15:39
add comment

3 Answers

up vote 5 down vote accepted

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.

share|improve this answer
Works as intended. Thanks. –  user1392060 Jul 18 '12 at 15:39
add comment

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)
share|improve this answer
Might be true. But I still needed the single bytes in a array. Thanks anyway. –  user1392060 Jul 18 '12 at 16:43
@user echo $bytes[0], $byte[1], $byte[2], $byte[3]; PHP strings are in essence byte arrays. –  deceze Jul 18 '12 at 16:45
Oh, ok! Excuse my ignorance then. Now that you mention it, I think that I might be overcomplicating things A LOT in PHP... –  user1392060 Jul 18 '12 at 17:08
add comment
$i = 123456;
$byte_array = unpack('C*', $i);

array(6) {
share|improve this answer
Sorry, but this seems wrong. The correct solution for "123456" is 64,226,1,0 as I posted. Besides, the array would have to contain 4 elements. Yours contains 6. (Integer is always 4bytes) –  user1392060 Jul 18 '12 at 15:33
hmm, you are right. PHP converts the integer to string in the unpack() call. sorry for the wrong answer. –  Jan Prieser Jul 18 '12 at 15:36
add comment

Your Answer


