17

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 ?

user1392060
  • 187
  • 1
  • 1
  • 6
  • 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? – deceze Jul 18 '12 at 15:36

2 Answers2

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.

Jon
  • 428,835
  • 81
  • 738
  • 806
6

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)
deceze
  • 510,633
  • 85
  • 743
  • 889