How to convert byte array to integer in php?

I saw code that converts an integer to an array of bytes . Below is the code in How to convert an integer array to a byte array in php 3 ( How to convert an integer value to a byte array in php ):

<?php $i = 123456; $ar = unpack("C*", pack("L", $i)); print_r($ar); ?> 

The above code outputs:

 //output: Array ( [1] => 64 [2] => 226 [3] => 1 [4] => 0 ) 

But now my problem is how to cancel this process. The conversion value from an array of bytes to an integer . In the above example, the output will be 123456

Can someone help me with this. I would really help. Thanks in advance.

+4
source share
3 answers

Why not treat it like a mathematical problem?

$ i = ($ ar [3] <24) + ($ ar [2] <16) + ($ ar [1] <8) + $ ar [0];

+9
source

Since L is four bytes long, you know the number of elements in the array. Therefore, you can simply perform the opposite operation:

 $ar = [64,226,1,0]; $i = unpack("L",pack("C*",$ar[3],$ar[2],$ar[1],$ar[0])); 
+4
source

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; 
+3
source

Source: https://habr.com/ru/post/1437314/


All Articles