Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert integer to byte array in php

Tags:

php

bytearray

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 ?

like image 347
user1392060 Avatar asked Jul 18 '12 15:07

user1392060


2 Answers

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.

like image 118
Jon Avatar answered Nov 05 '22 08:11

Jon


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)
like image 6
deceze Avatar answered Nov 05 '22 09:11

deceze