Beefy Boxes and Bandwidth Generously Provided by pair Networks Frank
Don't ask to ask, just ask
 
PerlMonks  

Re: Converting Hex to Float (and vise versa) (overly simple)

by tye (Sage)
on Feb 06, 2004 at 17:05 UTC ( [id://327237]=note: print w/replies, xml ) Need Help??

This is an archived low-energy page for bots and other anonmyous visitors. Please sign up if you are a human and want to interact.


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 05: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 ;

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://327237]
help
Sections?
Information?
Find Nodes?
Leftovers?
    Notices?
    hippoepoptai's answer Re: how do I set a cookie and redirect was blessed by hippo!
    erzuuliAnonymous Monks are no longer allowed to use Super Search, due to an excessive use of this resource by robots.