Why write your own hex decoder when there's good old sscanf()? A more
compact version:
$s = "40 3E 51 EB 85 1E B8 52";
$hex = sscanf($s, "%02x %02x %02x %02x %02x %02x %02x %02x");
$hex = array_reverse($hex);
$bin = implode('', array_map('chr', $hex));
$array = unpack("dnum", $bin);
echo $array['num'];
"Pedro Graca" <hexkid@dodgeit.com> wrote in message
news:slrncq51f6.1de.hexkid@ID-203069.user.uni-berlin.de...[color=blue]
> DvGrimm wrote:[color=green]
> > For example: I'm looking for a php function to convert (40 3E 51 EB 85[/color][/color]
1E[color=blue][color=green]
> > B8 52) hex to ($30.32) foating (double precision 64 bits)
> >
> > I'm not sure if this convertion is OS dependent??[/color]
>
> Probably (definitely?) it is.
>[color=green]
> > I'm using php and apache on WinXP (my laptop). But will be migrating[/color][/color]
to[color=blue][color=green]
> > code a Linux and apache server when complete.
> >
> > David[/color]
>[color=green]
> >================
> > The following code was posted by Chung Leong. This works very well from
> > floating point to hex, however, I require a php function to convert hex[/color][/color]
to[color=blue][color=green]
> > double precision floating point.
> >=================================[/color]
>
> I tool your example ("40 3E 51 EB 85 1E B8 52") as a string
>[color=green]
> > function ieee_double($f) {
> > $f = (double) $f;
> > $b = pack("d", $f);
> > $hex = "";
> > for($i = 0; $i < strlen($b); $i++) {
> > $c = ord($b{$i});
> > $hex .= sprintf(" %02X", $c);
> > } return $hex;
> > }[/color]
>
>
> First you have to reverse the for() loop;
> then the pack() call.
>
> I did it like this
>
>
> <?php
> function hexreverse($x) {
> $r = '';
> $y = explode(' ', $x);
> foreach ($y as $z) {
> $r = $z . ' ' . $r;
> }
> return substr($r, 0, -1);
> }
>
> function hexify($x) {
> static $v = array(
> '0'=>0, '1'=>1, '2'=>2, '3'=>3,
> '4'=>4, '5'=>5, '6'=>6, '7'=>7,
> '8'=>8, '9'=>9, 'A'=>10, 'B'=>11,
> 'C'=>12, 'D'=>13, 'E'=>14, 'F'=>15,
> 'a'=>10, 'b'=>11, 'c'=>12, 'd'=>13, 'e'=>14, 'f'=>15,
> );
> $r = '';
> $y = explode(' ', $x);
> foreach ($y as $z) {
> if (!ctype_xdigit($z)) return false;
> $tmp = $v[$z{0}] * 16 + $v[$z{1}];
> $r .= chr($tmp);
> }
> return $r;
> }
>
>
> $x0 = "40 3E 51 EB 85 1E B8 52";
> $x1 = hexreverse($x0); /* I need this: OS = Linux */
> $x2 = hexify($x1); /* reverse the for() loop; */
> if ($x2 === false) die("Invalid input\n");
> $x3 = unpack("d", $x2); /* reverse the pack() call */
> $y = $x3[1];
> var_dump($y); /* dump() the final value. */
> ?>
>
> --
> Mail sent to my "From:" address is publicly readable at[/color]
http://www.dodgeit.com/[color=blue]
> == ** ## !! !! ##[/color]
** ==[color=blue]
> TEXT-ONLY mail to the complete "Reply-To:" address ("My Name"[/color]
<my@address>) may[color=blue]
> bypass the spam filter. I will answer all pertinent mails from a valid[/color]
address.