Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations John Tel on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

cannot write a number to disk file in its binary format?

Status
Not open for further replies.

lichtjiang

Programmer
Feb 26, 2007
39
US
For example, say we want to write integer "100" in a binary file, "test.dat". The following code won't work.

$anumber=100;
$file="test.dat";
open(DAT, ">", $file);
print DAT $anumber;

This will write 3 bytes in "test.dat" as 31, 30, and 30. Though, if $anumber is read as "64" in hex from a binary file, then "64" can be written to "test.dat" in 1 byte.

It seems a scalar variable only writes its string value to disk file. Why? Any idea how to write a number's native value into a binary disk file? Thanks!
 
chr() can only work on a number that is of size of 1 byte. What about a number that takes more than 1 byte, say 1000. How to ensure this number is written to a binary file in 2 bytes?
 
I think you will have to split it up yourself:
1000 = 3*256 + 232
and so: chr(3), chr(232)
 
Thanks. That's also what I thought or maybe someone has done thiss before ...
 
though I think chr() can be very generic. but the problem can be better handled by "pack(...)" function, which is purposedly designed for writing binary data I guess.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top