How to convert byte array to integer in php? - 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.

Why not treat it like the math problem it is?
$i = ($ar[3]<<24) + ($ar[2]<<16) + ($ar[1]<<8) + $ar[0];

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]));

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;

Related

PHP remove first zero from decimals without round off

How to remove the first zero in a decimal number without round off.
whenever a function detect the first zero in decimal stop it and remove the zero and excess decimals.
I tried this:
$number = 1.063;
echo floor_dec($number,$deg);
function floor_dec($number, $deg = null)
{
if ($deg == null)
return $number * 1000 / 1000;
else
return $number * pow(10, $deg) / pow(10, $deg);
}
Desired output:
1.063 -> output 1
1.30720-> output 1.3
1.3072-> output 1.3
1.823070 -> output 1.823
Tricky one using strpos()
function removeFirstZeroToEnd($number)
{
$str = explode('.',$number);
if(isset($str[1])){
// find first zero after decimal
$num = substr($str[1],0, strpos($str[1], "0"));
// adding zero will convert it to number
$number = ($str[0].'.'.$num) + 0;
}
return $number;
}
Seems like this would be a lot easier by just treating it as a string and then just get the desired substring and then convert back to float:
floatval(rtrim(substr($number, 0, strpos($number, 0)), "."));
Obligatory regex solution:
$numbers = [
123,
1.063,
1.30720,
1.3072,
1.823070
];
foreach ($numbers as &$n) {
$n = preg_replace ('~^([0-9]+(\.[1-9]+)?).*~','$1',$n);
}
print_r($numbers);
Output:
Array
(
[0] => 123
[1] => 1
[2] => 1.3
[3] => 1.3
[4] => 1.823
)

Round up number to highest nearest 9 in laravel

I want to round up a number to highest nearest 9, Here is an example
(12,24,37,75,80)
if i gave this inputs want to get output like below given
(19,29,39,79,89)
I am using PHP(laravel), Please Help Me.
$input = [12,24,37,75,80];
$output = array_map(function($num) {
return (int)($num / 10) * 10 + 9;
}, $input);
I like the simplicity of #HTMHell's answer. And it works perfectly for integers. However, I found, that when using real numbers as input, something like 19.999 will be "rounded up" to 19.
I therefore suggest the following, modified version:
echo json_encode(array_map(function($v){
return ceil(($v+1)/10)*10-1;
},[12,18.99,19.01,24,37,75,80,90]));
// [19,19,29,29,39,79,89,99]
And, to answer #nice_dev's question, 90 should be rounded up to 99.
<?php
$items = array(12,24,37,75,80);
$endDigit = 9; //this should be between 0-9
$newItems = array();
foreach($items as $item){
$final = (int)($item / 10) * 10 + $endDigit;
array_push($newItems,$final);
}
print_r($newItems);
Output
Array ( [0] => 19 [1] => 29 [2] => 39 [3] => 79 [4] => 89 )

Convert a binary string to float in php

I get through Modbus some 4-Byte Float Values.
I get this 4 bytes in an array:
Array ( [0] => 67 [1] => 105 [2] => 25 [3] => 154 )
After some Bitconversion I made this:
1000011011010010001100110011010
when putting this binary string into a online converter such as
https://www.binaryconvert.com/result_float.html?hexadecimal=4369199A
I get the value of 2.331E2 which is correct (233.1).
However I fail to convert this binary in a PHP float variable. I tried to point the address to a float variable, but did not succeed.
How can I convert this binary string or the array above into a php float?
Added:
The pointer Idea was stupid, since php does not let me define the type of variable. So I tried a different approach using unpack to a float type. But it does not work either:
// This represents a 4 byte float read from modbus
$array=array(67,105,25,154);
$array=array_reverse($array);
print_r($array);
for ($i=0;$i<count($array);$i++) {
$t+=pow(2,$i*8)*$array[$i];
}
echo '<br>Binary: '.decbin($t). ' - This would be the correct Binary for 233.1';
echo '<br>float: ';
print_r(unpack('f',$t));
This code results in:
Array ( [0] => 154 [1] => 25 [2] => 105 [3] => 67 )
Binary: 1000011011010010001100110011010 - This would be the correct Binary for 233.1
float: Array ( [1] => 6.5189725839687E-10 )
No chance to get my 233.1 :(
I know I come with a possible answer a little bit later but maybe others found useful.
The conversion is a little bit complicated, I worked few hours on it to include in my application.
Firstly I created a function to get value of the Mantissa, then calculated a float number. I didn't created function for the calculation of the exponent and sign.
This example is valid for positive float numbers, for more details read this:
HOW REAL (FLOATING POINT) AND 32-BIT DATA IS ENCODED IN MODBUS RTU MESSAGES
And the script:
$array=array(67,105,25,154);
$result = pow(2,(((($array[0] * 256 + $array[1]) & 32640) >> 7)-127)) * calcMantissa((($array[1] & 127) << 16) + ($array[2] << 8) + $array[3]+1);
echo $result . "\n";
function calcMantissa($nb) {
$retValue = 1;
for ($i = 0; $i < 22; $i++) {
$retValue = $retValue + (($nb & (1 << (22 - $i))) > 0) / (pow(2,($i+1))) ;
}
return $retValue;
}
which gave the following result:
233.10000610352

Use PHP ord() function for an entire text

I know that the PHP ord() function converts a certain character to ASCII. But I want to build a web application that encrypts an inputted text using several methods, and I want to implement a "Text to ASCII" method.
I tried to use the ord() function for each character from the inputted string $text. That's my code:
for ($i = 0; $i<strlen($text); $i++)
$text[$i] = ord($text[$i]);
The problem is, the characters aren't converted properly.
I also tried using $i<=strlen($text);, but it just spams my page with some type of error, and I'm pretty sure $i doesn't need to reach strlen($text) exactly.
What can I do?
The code is overwriting the string it is trying to convert. Also ord() can produce multiple characters per input character, so this will produce more confusion.
Instead you could build an array for each character, several ways to do it, but sticking with the current method(ish)...
$text = "Hello";
$chrs = [];
for ($i = 0; $i<strlen($text); $i++) {
$chrs[] = ord($text[$i]);
}
print_r($chrs);
gives an output of...
Array
(
[0] => 72
[1] => 101
[2] => 108
[3] => 108
[4] => 111
)

PHP rand explanation using an array?

I have very little programming experience but I am going over a php book and this block of code is confusing me.
If rand generates a random integer, how does this program use ABCDEFG in the array.
Can you please explain the program thank you. I know what the result is, I am just not sure how it get it.
<?php
$array = '123456789ABCDEFG';
$s = '';
for ($i=1; $i < 50; $i++) {
$s.= $array[rand(0,strlen($array)-1)]; //explain please
}
echo $s;
?>
It's using the array index so $array[11] would equal 'C'. rand() takes a range - in your example that's from 0 to strlen($array)-1 which is the length of the string, minus 1 since it's a 0 based index.
Break it down into parts:
strlen($array) - returns the length of the string in $array, which would be 17
strlen($array) - 1 => 16
rand(0, 16) - generate a random number between 0 and 16
$array[$random_number] - get the $random_number'th element of the array
Its just taking the length of the array with strlen($array). It doesn't matter what is in the string just the length. Then its generating a random number between 0 and the length of the string minus one.
Then it takes whatever character is in that position in the array (so $array[5] would be '6', $array[12] would be 'C', etc) and appending that to string $s. It then has a for loop to repeat it 50 times.
What you end up with is a random string that is 50 characters long and contains the numbers 1-9 and letters A-G.

Categories