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 ?
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With