简体   繁体   中英

Convert hexadecimal number to double

The string of the hexadecimal number is like: 0X1.05P+10

The real value of this hexadecimal number is:1044.0

I can convert it using C language with method strtod. But I can't find the way to convert it in PHP. Can somebody show me how to do it?

value string list:

1. "0X1.FAP+9"
2. "0X1.C4P+9"
3. "0X1.F3P+9"
4. "0X1.05P+10"

hexdec(0X1.05P+10)

OK so that looks wrong to me as that doesn't look like a proper hex number but its the hexdec() function you want in php http://php.net/manual/en/function.hexdec.php

echo hexdec("0X1FAP")+9
echo hexdec("0X1C4P")+9
echo hexdec("0X1F3P")+9
echo hexdec("0X105P")+10

decimal = hex (1044.0) 10 = (414) 16

I think you'll have to make a custom function for this. So because I'm feeling nice today I custom-made one for you:

function strtod($hex) {
    preg_match('#([\da-f]+)\.?([\da-f]*)p#i', $hex, $parts);

    $i = 0;
    $fractional_part = array_reduce(str_split($parts[2]), function($sum, $part) use (&$i) {
        $sum += hexdec($part) * pow(16, --$i);

        return $sum;
    });

    $decimal = (hexdec($parts[1]) + $fractional_part) * pow(2, array_pop(explode('+', $hex)));  

    return $decimal;
}

foreach(array('0X1.FAP+9', '0X1.C4P+9', '0X1.F3P+9', '0X1.05P+10', '0X1P+0') as $hex) {
    var_dump(strtod($hex));
};

For versions below PHP 5.3:

function strtod($hex) {
    preg_match('#([\da-f]+)\.?([\da-f]*)p#i', $hex, $parts);

    $fractional_part = 0;

    foreach(str_split($parts[2]) as $index => $part) {
        $fractional_part += hexdec($part) * pow(16, ($index + 1) * -1);
    }

    $decimal = (hexdec($parts[1]) + $fractional_part) * pow(2, array_pop(explode('+', $hex)));  

    return $decimal;
}

foreach(array('0X1.FAP+9', '0X1.C4P+9', '0X1.F3P+9', '0X1.05P+10', '0X1P+0') as $hex) {
    var_dump(strtod($hex));
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM