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

Re: decimal to binary?

Thread Previous | Thread Next
Chas. Owens
September 23, 2009 13:21
Re: decimal to binary?
Message ID:
On Wed, Sep 23, 2009 at 15:32, Bob McConnell <> wrote:
> From: Uri Guttman
>>>>>>> "BM" == Bob McConnell <> writes:
>>   BM> From: Bryan R Harris
>>   >>
>>   >> 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
>>   BM> bc 93
>>   >> d3  (I just made up those 8 byte values).
>>   >>
>>   >> Is this easy in perl?  Are long and short ints easy as well?
>>   BM> The sprintf() family is your friend.
>> that will only generate text (hex and other formats). he needs pack
>> which does exactly what he wants. read perlpacktut for a tutorial on
>> pack/unpack and then perlfunc -f pack for the reference on it.
> That statement just confuses me. His initial value of -3205.0569059 is
> also text. It is the human readable representation of the number, and is
> not anything like what it looks like inside the computer. He just asked
> for a different format for that text. Why is sprintf not a reasonable
> way to do that?

Because sprintf "%16x", .5 returns "0000000000000000" and you can't
recover .5 from that.  On the other hand you can say:

use strict;
use warnings;

my $n        = -3205.0569059;
my $packed   = pack "d", $n;
my $hex      = unpack "H*", $packed;
my $unpacked = unpack "d", pack "H*", $hex;
	"n        = $n\n",
	"packed   = $packed\n",
	"hex      = $hex\n",
	"unpacked = $unpacked\n";

Chas. Owens
The most important skill a programmer can have is the ability to read.

Thread Previous | Thread Next Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at | Group listing | About