php convert decimal to hexadecimal - php

I am extracting a serial from a digital certificate using the built-in OpenSSL library, however, I am having trouble converting this number to hex with precision.
The extracted number is originally in decimal but I need to have it in hex.
The number I am trying to convert is: 114483222461061018757513232564608398004
Here is what I've tried:
dechex() did not work, it returns: 7fffffffffffffff
The closest I could get was this function from the php.net page but it does not convert the whole number on part of it.
function dec2hex($dec) {
$hex = ($dec == 0 ? '0' : '');
while ($dec > 0) {
$hex = dechex($dec - floor($dec / 16) * 16) . $hex;
$dec = floor($dec / 16);
}
return $hex;
}
echo dec2hex('114483222461061018757513232564608398004');
//Result: 5620aaa80d50fc000000000000000000
Here is what I am expecting:
Decimal number: 114483222461061018757513232564608398004
Expected hex: 5620AAA80D50FD70496983E2A39972B4
I can see the correction conversion here:
https://www.mathsisfun.com/binary-decimal-hexadecimal-converter.html
I need a PHP solution.

The problem is that The largest number that can be converted is ... 4294967295 - hence why it's not working for you.
This answer worked for me during a quick test, assuming you have bcmath installed on your server, and you can obtain the number as a string to start with. If you can't, i.e. it begins life as numeric variable, you'll immediately reach PHP's float limit.
// Credit: joost at bingopaleis dot com
// Input: A decimal number as a String.
// Output: The equivalent hexadecimal number as a String.
function dec2hex($number)
{
$hexvalues = array('0','1','2','3','4','5','6','7',
'8','9','A','B','C','D','E','F');
$hexval = '';
while($number != '0')
{
$hexval = $hexvalues[bcmod($number,'16')].$hexval;
$number = bcdiv($number,'16',0);
}
return $hexval;
}
Example:
$number = '114483222461061018757513232564608398004'; // Important: already a string!
var_dump(dec2hex($number)); // string(32) "5620AAA80D50FD70496983E2A39972B4"
Ensure you pass a string into that function, not a numeric variable. In the example you provided in the question, it looks like you can obtain the number as a string initially, so should work if you have bc installed.

Answered by lafor.
How to convert a huge integer to hex in php?
function bcdechex($dec)
{
$hex = '';
do {
$last = bcmod($dec, 16);
$hex = dechex($last).$hex;
$dec = bcdiv(bcsub($dec, $last), 16);
} while($dec>0);
return $hex;
}
Example:
$decimal = '114483222461061018757513232564608398004';
echo "Hex decimal : ".bcdechex($decimal);

This is a big integer, so you need to use a big-integer library like GMP:
echo gmp_strval('114483222461061018757513232564608398004', 16);
// output: 5620aaa80d50fd70496983e2a39972b4

Try this 100% working for any number
<?php
$dec = '114483222461061018757513232564608398004';
// init hex array
$hex = array();
while ($dec)
{
// get modulus // based on docs both params are string
$modulus = bcmod($dec, '16');
// convert to hex and prepend to array
array_unshift($hex, dechex($modulus));
// update decimal number
$dec = bcdiv(bcsub($dec, $modulus), 16);
}
// array elements to string
echo implode('', $hex);
?>

Related

PHP Math fail (hexadecimal)

Im trying to do a php multiplication of two 32bit long hexadecimal valuey with PHP and it seems it is messing up this calculation, the same happens if i multiplicate it as decimal value.
The calculation is as example:
0xB5365D09 * 0xDEBC252C
Converting to decimal before with hexdec doesnt change anything.
The expected result should be 0x9DAA52EA21664A8C but PHPs result is 0x9DAA52EA21664800
Example:
<?php
$res = 0xB5365D09 * 0xDEBC252C;
echo dechex(intval($res));
?>
What i am doing wrong here?
PHP8.2 running on debian, 64bit AMD.
So, for others to find the answer:
Someone stated in the comments to my question, that the result is above the PHP_MAX_INT limit. So when PHP handle it as a FLOAT, there will be some precision of the result lost. I got it to work using bcmath. In my case, i didnt do math with the result any further so i grabbed some piece of code from here, and made a simple function which does what i need. Here you can see a minimum-example:
function bcmul_hex($h1, $h2) {
$dec = bcmul($h1, $h2);
$hex = '';
do {
$last = bcmod($dec, 16);
$hex = dechex($last).$hex;
$dec = bcdiv(bcsub($dec, $last), 16);
} while($dec>0);
return $hex;
}
echo bcmul_hex(0xB5365D09, 0xDEBC252C);
Here is a live example.
If you're trying to perform a mathematical operation on a hexadecimal value in PHP, you can use the hexdec function to convert the hexadecimal value to a decimal value, perform the operation, and then use the dechex function to convert the result back to a hexadecimal value.
Here's an example:
<?php
$hex1 = "B5365D09";
$hex2 = "DEBC252C";
// Convert hexadecimal values to decimal
$dec1 = hexdec($hex1);
$dec2 = hexdec($hex2);
// Perform multiplication operation
$result = $dec1 * $dec2;
// Convert result back to hexadecimal
$hex_result = dechex($result);
// Print result
echo "Result: $hex_result\n";
This code will output the result of the multiplication as a hexadecimal value.

How to convert a large binary string to a binary value and back

I need to take a large binary string (whose length will always be divisible by 8) ...
// 96-digit binary string
$str = '000000000011110000000000000000001111111111111111111111111111111111111111000000000000000000001111';
... then convert it to a binary value (to store in a mysql db as type varbinary), and later convert it back again to recreate that string.
This is most likely NOT a duplicate question. Every posted stackoverflow answer I could find is either broken (PHP7 apparently changed how some of these functions work) or doesn't offer a solution to this specific problem. I've tried a few things, such as ...
// get binary value from binary string
$bin = pack('H*', base_convert($str, 2, 16));
// get binary string from binary value
$str2 = str_pad(base_convert(unpack('H*', $bin)[1], 16, 2), 96, 0, STR_PAD_LEFT);
... but this doesn't actually work.
My goal is to go back and forth between the given binary string and the smallest binary value. How is this best done?
These functions convert bit strings to binary character strings and back.
function binStr2charStr(string $binStr) : string
{
$rest8 = strlen($binStr)%8;
if($rest8) {
$binStr = str_repeat('0', 8 - $rest8).$binStr;
}
$strChar = "";
foreach(str_split($binStr,8) as $strBit8){
$strChar .= chr(bindec($strBit8));
}
return $strChar;
}
function charStr2binStr(string $charStr) : string
{
$strBin = "";
foreach(str_split($charStr,1) as $char){
$strBin .= str_pad(decbin(ord($char)),8,'0', STR_PAD_LEFT);
}
return $strBin;
}
usage:
// 96-digit binary string
$str = '000000000011110000000000000000001111111111111111111111111111111111111111000000000000000000001111';
$strChars = binStr2charStr($str);
// "\x00<\x00\x00\xff\xff\xff\xff\xff\x00\x00\x0f"
//back
$strBin = charStr2binStr($strChars);

PHP convert hex to float

Hi I am trying to convert the hex value into float the method I am using is
function hex2float($strHex) {
$hex = sscanf($strHex, "%02x%02x%02x%02x%02x%02x%02x%02x");
$hex = array_reverse($hex);
$bin = implode('', array_map('chr', $hex));
$array = unpack("dnum", $bin);
return $array['num'];
}
$float = hex2float('4019999a');
echo $float;
Output
The output it's returning is 6.4000015258789 but in actual it should be 2.4
See reference
Your problem is that you are interpreting the value in little endian byte order. This gives you the incorrect value of 6.4, which is actually -6.3320110435437E-23. Additionally, you are unpacking this as a double-precision float. It's not. It's single precision (only 4 bytes wide).
function hex2float($strHex) {
$hex = sscanf($strHex, "%02x%02x%02x%02x%02x%02x%02x%02x");
$bin = implode('', array_map('chr', $hex));
$array = unpack("Gnum", $bin);
return $array['num'];
}
$float = hex2float('4019999a');
echo $float;
This gives you the correct value of 2.4.
An easier way to do this is var_dump(unpack('G', hex2bin('4019999a'))[1]); which also gives you the correct value.

Why I am getting output 0 while trying to convert a huge integer to hex in php?

I'm trying to convert big int to hex in php
I have tried this function from How to convert a huge integer to hex in php?
<?php
function bcdechex($dec) {
$hex = '';
do {
$last = bcmod($dec, 16);
$hex = dechex($last).$hex;
$dec = bcdiv(bcsub($dec, $last), 16);
} while($dec>0);
return $hex;
}
$int = 115792089237316195423570985008687907852837564279074904382605163141518161494336 ;
$int_to_hex = strtoupper( bcdechex ( $int )) ;
echo $int_to_hex ;
It gives output as 0
I've tried above code in WAMP and LAMP
I've latest php, bcmath, gmp installed.
What am I doing wrong ?
I'm trying to generate hex to use creating bitcoin address
usually int
115792089237316195423570985008687907852837564279074904382605163141518161494336
gives HEX
FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364140
update 1 :
i have verified that bcmath is installed and loaded.
php -m | grep bcmath
bcmath
update 2:
i tried
$int = 115792089237316195423570985008687907852837564279074904382605163141518161494336 ;
echo dechex($int);
gives
0
i tried smaller int
$int = 556 ;
echo dechex($int);
gives
22c
update 3 :
as suggested by Mikethetechy
$int = 123456789 ;
echo dechex($int);
75bcd15
$int = "123456789" ;
echo dechex($int);
75bcd15
update 4 :
Issue solved by putting big int in quotes
i.e. using
$int = '115792089237316195423570985008687907852837564279074904382605163141518161494336';
instead of
$int = 115792089237316195423570985008687907852837564279074904382605163141518161494336;
This works.
<?php
function bcdechex($dec) {
$hex = '';
do {
$last = bcmod($dec, 16);
$hex = dechex($last).$hex;
$dec = bcdiv(bcsub($dec, $last), 16);
} while($dec>0);
return $hex;
}
$int = '115792089237316195423570985008687907852837564279074904382605163141518161494336';
$int_to_hex = strtoupper( bcdechex ( $int )) ;
echo $int_to_hex ;
Can google up on arbitrary precision. Your system will have limitations on floats and integer values based on hardware and environment settings. I've used gmp for things like this - ideas is you use a resource, string whatever and represent it that way to work with it. The bc functions also expect strings! That function divides up the string, you manipulate it, and then you concatenate your results to form the output.
Good thing to look at might be: https://github.com/phpseclib/phpseclib/blob/master/phpseclib/Math/BigInteger.php

Convert a string containing a number in scientific notation to a double in PHP

I need help converting a string that contains a number in scientific notation to a double.
Example strings:
"1.8281e-009"
"2.3562e-007"
"0.911348"
I was thinking about just breaking the number into the number on the left and the exponent and than just do the math to generate the number; but is there a better/standard way to do this?
PHP is typeless dynamically typed, meaning it has to parse values to determine their types (recent versions of PHP have type declarations).
In your case, you may simply perform a numerical operation to force PHP to consider the values as numbers (and it understands the scientific notation x.yE-z).
Try for instance
foreach (array("1.8281e-009","2.3562e-007","0.911348") as $a)
{
echo "String $a: Number: " . ($a + 1) . "\n";
}
just adding 1 (you could also subtract zero) will make the strings become numbers, with the right amount of decimals.
Result:
String 1.8281e-009: Number: 1.0000000018281
String 2.3562e-007: Number: 1.00000023562
String 0.911348: Number: 1.911348
You might also cast the result using (float)
$real = (float) "3.141592e-007";
$f = (float) "1.8281e-009";
var_dump($f); // float(1.8281E-9)
Following line of code can help you to display bigint value,
$token= sprintf("%.0f",$scienticNotationNum );
refer with this link.
$float = sprintf('%f', $scientific_notation);
$integer = sprintf('%d', $scientific_notation);
if ($float == $integer)
{
// this is a whole number, so remove all decimals
$output = $integer;
}
else
{
// remove trailing zeroes from the decimal portion
$output = rtrim($float,'0');
$output = rtrim($output,'.');
}
I found a post that used number_format to convert the value from a float scientific notation number to a non-scientific notation number:
Example from the post:
$big_integer = 1202400000;
$formatted_int = number_format($big_integer, 0, '.', '');
echo $formatted_int; //outputs 1202400000 as expected
Use number_format() and rtrim() functions together. Eg
//eg $sciNotation = 2.3649E-8
$number = number_format($sciNotation, 10); //Use $dec_point large enough
echo rtrim($number, '0'); //Remove trailing zeros
I created a function, with more functions (pun not intended)
function decimalNotation($num){
$parts = explode('E', $num);
if(count($parts) != 2){
return $num;
}
$exp = abs(end($parts)) + 3;
$decimal = number_format($num, $exp);
$decimal = rtrim($decimal, '0');
return rtrim($decimal, '.');
}
function decimal_notation($float) {
$parts = explode('E', $float);
if(count($parts) === 2){
$exp = abs(end($parts)) + strlen($parts[0]);
$decimal = number_format($float, $exp);
return rtrim($decimal, '.0');
}
else{
return $float;
}
}
work with 0.000077240388
I tried the +1,-1,/1 solution but that was not sufficient without rounding the number afterwards using round($a,4) or similar

Categories