php - Convert hexadecimal number to double -
the string of hexadecimal number like: 0x1.05p+10
the real value of hexadecimal number is:1044.0
i can convert using c language method strtod. can't find way convert in php. can show me how it?
value string list:
1. "0x1.fap+9" 2. "0x1.c4p+9" 3. "0x1.f3p+9" 4. "0x1.05p+10"
i think you'll have make custom function this. because i'm feeling nice today custom-made 1 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') $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]) $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') $hex) { var_dump(strtod($hex)); };
Comments
Post a Comment