Nov 26, 2010, 12:37 PM
Post #1 of 2
Strange behavior on 32-bit Value 10 in big-endian w/ print?
I am struggling with a problem I have.
Currently I am working on a file format and when writing numbers, I pack() them with into a 32-bit big-endian sequence (network order).
I now want write this four byte sequence into a file,
This is, when things seem to go magical. I would expect that exact four bytes are written into the file, because
print $my_fh pack("N", $num_to_pack);
is always 4, even if use bytes; is activated. In nearly every case, the resulting sequence in the file is four bytes long and in correct order. BUT, if my value is 10, the Sequence written will be "00 00 00 0D 0A", that is five bytes.
length pack("N", $num_to_pack)
At first, I thought this would happen only in my program, because it is not that uncomplex. But then, I tested the following code as-is:
and checked "out"'s contents. Guess what? "00 00 00 0D 0A 00 00 00 0D 0A". So am I totally missing something or what is going on here?
open F, ">", "out"
or die "Cannot open: $!\n";
my $val = 10;
print(F pack("N", $val));
printf(F "%4s", pack("N", $val));
I so hope this has just something to do with the \r\n thingy, because 0D is 13 in hex. And 13 10... Well, does not seem that random to me :P.
Nevertheless I was pretty surprised by this behavior, help thus would be appreciated.