develooper Front page | perl.beginners | Postings from September 2009

Re: decimal to binary?

Thread Previous | Thread Next
From:
Shawn H Corey
Date:
September 23, 2009 14:31
Subject:
Re: decimal to binary?
Message ID:
4ABA9362.6070700@gmail.com
Bryan R Harris wrote:
>> Bryan R Harris wrote:
>>> I need to convert a number like this:   -3205.0569059
>>> ... into an 8-byte double (big and little endian), e.g. 4f 3e 52 00 2a bc 93
>>> d3  (I just made up those 8 byte values).
>>>
>>> Is this easy in perl?  Are long and short ints easy as well?
>> $ perl -le'print unpack "H*", pack "d", -3205.0569059'
>> e626c5221d0aa9c0
> 
> 
> Maybe this is just my own ignorance on big-endian vs. little endian, but
> this code:
> 
>   print "big-endian:     ", unpack("H*", pack("d", -3205.0569059)), "\n";
>   print "little-endian:  ", unpack("h*", pack("d", -3205.0569059)), "\n";
> 
> prints:
> 
>   big-endian:     e626c5221d0aa9c0
>   little-endian:  6e625c22d1a09a0c
> 
> ... when I expected the little endian to look more like:
> 
>   c0 a9 0a 1d 22 c5 26 e6   (spacing for readability)
> 
> Did I do it wrong (i.e. is "h*" the wrong string?), or am I confused on how
> big vs. little endian works?
> 
> Thanks again for the help!!  This list is terrific!

 From `perldoc -f pack`:

Real numbers (floats and doubles) are in the native machine format only; 
due to the multiplicity of floating formats around, and the lack of a 
standard "network" representation, no facility for interchange has been 
made.  This means that packed floating point data written on one machine 
may not be readable on another - even if both use IEEE floating point 
arithmetic (as the endian-ness of the memory representation is not part 
of the IEEE spec).  See also perlport.



-- 
Just my 0.00000002 million dollars worth,
   Shawn

Programming is as much about organization and communication
as it is about coding.

I like Perl; it's the only language where you can bless your
thingy.

Thread Previous | Thread Next


nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About