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.
We can convert the byte array to String for the ASCII character set without even specifying the character encoding.
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) .
1.1. To convert a byte array to String , you can use String class constructor with byte[] as constructor argument.
Why not treat it like the math problem it is?
$i = ($ar[3]<<24) + ($ar[2]<<16) + ($ar[1]<<8) + $ar[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