Raymond Wan wrote:
Hi all,

Hello,

I would like to write binary values to disk (as well as read them) but don't
know how to do it.  In C-speak, something like this:

unsigned int foo = 42;
fwrite (&foo, sizeof (unsigned int), 1, stdout);

I think the answer involves something with pack and unpack, but I'm
completely lost as I have no experience with either.  The closest I got was

my $decimal_number = 42;
my $binary_number = unpack("B32", pack("N", $decimal_number));
print "Decimal number " . $decimal_number . " is " . $binary_number .
" in binary.\n\n";

In Perl numbers and strings are interchangable so:

my $decimal_number = 42;

and

my $decimal_number = '42';

and

my $decimal_number = "42";

all do the same thing.  You could also write that as:

my $decimal_number = 052;  # octal representation of 42

or:

my $decimal_number = 0x2A;  # hexadecimal representation of 42

or:

my $decimal_number = 0b101010;  # binary representation of 42

See:

perldoc perlnumber

for more details.

The C binary number 42 is represented in Perl as a string:

my $decimal_number = "\x2A";

or:

my $decimal_number = "\052";

That is equivalent in C to:

unsigned char decimal_number = 42;

Or another way to write that in Perl is:

my $decimal_number = pack 'C', 42;


Once you have created the appropriate strings using pack() then just print() them.



John
--
Those people who think they know everything are a great
annoyance to those of us who do.        -- Isaac Asimov

--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/


Reply via email to