Dealing with Binary Data

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
agravayne
Forum Newbie
Posts: 8
Joined: Thu Dec 04, 2008 4:55 am

Dealing with Binary Data

Post by agravayne »

Hello,

I am trying to get my head around dealing with binary data and PHP - not having great success.

At present I want to parse in binary data from a file in chunks. As an example this is my tet php.

Code: Select all

$filename="test.bin";
$handle=fopen($filename,"rb");
$byte=fread($handle,1);
fclose($handle);
echo "1st byte is $byte";
Now this reads the first byte from my test file. This is 01 when viewed in a Hex editor so Binary 00000001 and 1 in decimal. I know I am reading the value correctly - if I write it back into a new binary file it shows as 01 again so the vlue is correct. But the echo above display just a nonsense charcater. How do I convert the variable $byte into either a decimal value or a binary value that I can manipulate in PHP?

Many thanks
Scott
Mark Baker
Forum Regular
Posts: 710
Joined: Thu Oct 30, 2008 6:24 pm

Re: Dealing with Binary Data

Post by Mark Baker »

ord() and chr()
agravayne
Forum Newbie
Posts: 8
Joined: Thu Dec 04, 2008 4:55 am

Re: Dealing with Binary Data

Post by agravayne »

That would give me the equivalent ascii code and I want the numerical value. It doesn''t work anyway as chr needs the decimal number passed to it and the variable $byte is not a deciaml number its pure binary.
User avatar
Eran
DevNet Master
Posts: 3549
Joined: Fri Jan 18, 2008 12:36 am
Location: Israel, ME

Re: Dealing with Binary Data

Post by Eran »

Post Reply