Reputation: 527
I have seen a code that converts integer into byte array. Below is the code on How to convert integer to byte array in php 3 (How to convert integer to byte array in php):
<?php
$i = 123456;
$ar = unpack("C*", pack("L", $i));
print_r($ar);
?>
The above code will output:
//output:
Array
(
[1] => 64
[2] => 226
[3] => 1
[4] => 0
)
But my problem right now is how to reverse this process. Meaning converting from byte array into integer. In the case above, the output will be 123456
Can anybody help me with this. I would be a great help. Thanks ahead.
Upvotes: 8
Views: 12947
Reputation: 131
In order to get a signed 4-byte value in PHP you need to do this:
$temp = ($ar[0]<<24) + ($ar[1]<<16) + ($ar[2]<<8) + $ar[3];
if($temp >= 2147483648)
$temp -= 4294967296;
Upvotes: 4
Reputation: 484
Why not treat it like the math problem it is?
$i = ($ar[3]<<24) + ($ar[2]<<16) + ($ar[1]<<8) + $ar[0];
Upvotes: 11
Reputation: 324630
Since L is four bytes long, you know the number of elements of the array. Therefore you can simply perform the operation is reverse:
$ar = [64,226,1,0];
$i = unpack("L",pack("C*",$ar[3],$ar[2],$ar[1],$ar[0]));
Upvotes: 5