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 biv343 on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How to store an integer inside a file using only 4 bytes? 1

Status
Not open for further replies.

RbgoWeb

Programmer
Apr 10, 2002
91
NL
An integer number in its decimal representation has a display size of max. 10 text characters. When writing this integer to a file, php/fwrite uses the same text format.

How can I store it by value instead of text, so the integer only takes up the 4 bytes (or 32 bits) that it (often) consists of?
 
You might try opening up your file in binary mode and writing an integer to it. I dont know as that will work, but it might. fopen(...,"wb);



Robert Carpenter
"You and I have need of the strongest spell that can be found to wake us from the evil enchantment of worldliness." - C.S. Lewis (The Weight of Glory)

robert (at) robertcarpenter (dot) net
 
I had to both use the "b" flag when opening the file and use the pack() function.

This script:
Code:
<?php
$fh = fopen ('foo.txt', 'wb');
$a = pack ('l', 125896);
fputs ($fh, $a);
fclose ($fh);
?>

Creates a file which on my LAMP box consists entirely of the hex values 0xC8 0xEB 0x01 0x00

This script:
Code:
<?php
$fh = fopen ('foo.txt', 'rb');
$a = unpack ('l', fgets ($fh));
fclose ($fh);
print $a[1];
?>

Outputs 125896




Want the best answers? Ask the best questions!

TANSTAAFL!!
 
pack() and unpack() does exactly what I was looking for.
Thanks a lot sleipnir.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top