Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert byte array to integer in php?

Tags:

php

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.

like image 581
gchimuel Avatar asked Oct 02 '12 02:10

gchimuel


People also ask

Can we convert byte array to String?

We can convert the byte array to String for the ASCII character set without even specifying the character encoding.

How to convert byte code into String?

Convert byte[] to String (text data) toString() to get the string from the bytes; The bytes. toString() only returns the address of the object in memory, NOT converting byte[] to a string ! The correct way to convert byte[] to string is new String(bytes, StandardCharsets. UTF_8) .

What are the constructors used for creating a String with byte array?

1.1. To convert a byte array to String , you can use String class constructor with byte[] as constructor argument.


1 Answers

Why not treat it like the math problem it is?

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

like image 137
PRB Avatar answered Sep 17 '22 01:09

PRB