简体   繁体   English

将十六进制数转换为双精度

[英]Convert hexadecimal number to double

The string of the hexadecimal number is like: 0X1.05P+10 十六进制数字的字符串类似于:0X1.05P + 10

The real value of this hexadecimal number is:1044.0 该十六进制数的实际值为:1044.0

I can convert it using C language with method strtod. 我可以使用C语言的strtod方法进行转换。 But I can't find the way to convert it in PHP. 但是我找不到在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 好的,这对我来说似乎是错误的,因为它看起来不像是正确的十六进制数字,但它是您在php http://php.net/manual/en/function.hexdec.php中想要的hexdec()函数

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

decimal = hex (1044.0) 10 = (414) 16 十进制=十六进制(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: 对于低于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));
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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