in reply to Converting Hex to Float (and vise versa)

This should work on many platforms for the example data you gave:

my $float= unpack "f", pack "L", 0x428C0000;

(assuming the value you wanted was the nice-looking "70").

but I'm not sure how to reconcile the terms "in ASCII" vs. "e.g. 0x428C0000". Perhaps you have a string like "0x428C0000":

my $string= "0x428C0000"; my $float= unpack "f", pack "L", hex $string;
or perhaps you have a string of bytes whose hex values are 42, 8C, 00, and 00:
my $string= "\x42\x8C\x00\x00";
in which case you could pick between these two, depending on whether the source and destination systems are the same or different endian:
$float= unpack "f", $string; $float= unpack "f", scalar reverse $string;
or you could use use two steps to auto-handle the receiving ends endianness (since your example data appears to show me the endianness of the source):
my $string= "\x42\x8C\x00\x00"; my $float= unpack "f", pack "L", unpack "N", $string;

- tye        

Replies are listed 'Best First'.
Re: Re: Converting Hex to Float (and vise versa) (overly simple)
by Anonymous Monk on Feb 07, 2004 at 10:34 UTC

    $float= unpack "f", pack "L", 0x428C0000;
    print $float; # 70
    $float= unpack "L", pack "f", 70 ;
    print $float; # print 1116471296

    Please tye, could you just point me why?

        Thanks, but the thing which hurt me is the 'no-symmetry':

        $float= unpack "f", pack "L", 0x428C0000; # $float is 70 $float= sprintf("%lx", unpack "L", pack "f", 70 ); print $float; # print 428C0000

        I take this as a fact but I don't understand why the exact
        opposite expression doesn't give back the original data:
        $is_not_hex = unpack "L", pack "f", 70 ;