in reply to Converting Hex to Float (and vise versa)
It's even more complex than that, you have to take into account the architecture of the CPU as well. When I did this I found it most usefull to start from floats and get to the hex. I also did it via binary:
$f2_5 = unpack("b64",pack("d",2.5)); print $f2_5 . "\n"; # Will return something like 00000000000000000000000000000000000000000 +00000000010000000000010
What I have done is to convert hex to binary then (possibly) shuffle the binary to a form suitable for this CPU and use pack/ unpack to assemble the float.
{ my($endian,$binary2double_fun); sub deduce_endian { my($v); # Deduce the machine's native FP format by encoding the # number 2.5 as a bit string. Once we know how to get # from doubles to bit strings we can deduce the function # for doing the reverse $v = unpack("b64",pack("d",2.5)); if($v eq "00000000000000000000000000000000000000000000000000100000 +00000010") { # Intel or something like it $endian = "ieee-little"; $binary2double_fun = sub { # We have to reverse the bitstring my $bits = reverse(shift); # Then map to floats return(unpack("d",pack("b64",$bits))); }; } elsif($v eq "01000000000001000000000000000000000000000000000000000 +00000000000") { # *NIX hardware $endian = "ieee-big"; $binary2double_fun = sub { # a combination of pack and unpack will do it my $bits = shift; return(unpack("d",pack("b64",$bits))); }; } else { print STDERR "Not configured for this machine yet\n"; exit(20); } } sub hex2double { my($in,$out,$val) = @_; deduce_endian() if(!$endian); # The string we were given was a hex representation of # the bits of an IEEE 64' double in network order. # Convert to a string of 64 "0" and "1"s. We cannot # use pack here because then the order depends on the # hardware $out = hex2binary($in); # Then map this to our double representation return &{$binary2double_fun}($out) if($binary2double_fun); # No mapping function defined! return 0.0; } }
I have my own hex2binary function for various reasons that are not worth dwelling on. It sounds like you want one that takes into account the byte order of the input.
|
|---|