|
Posted by Richard Brooks on 03/12/07 19:56
Mathias K. said the following on 11/03/07 16:52:
> Hello everyone!
>
> I'm currently dealing a lot with binary data.
> Therefore it is sometimes that i have to read or write
> single bits. What is the best way to do that?
>
> For example let it be one single byte where the first 5 bits
> contain a certain information, and the rest belongs to the next
> binary block.
>
> Now i get those 5 bits as follows: <<<PHP
>
> // $fp is a filepointer to an open binary file
>
> $byte = fread($fp, 1); // one byte
> $bin = decbin( ord( $byte ) );
>
> $fivebits = bindec( substr($byte, 0, 5) );
>
> PHP;
>
> Well that seems kind of long winded to me.
> Isn't there are better, quicker and more elegant way to do that in PHP?
> Because right now i don't know of any.
>
>
> Thanks for any hints in advance.
>
> ~ MK
<http://theopensourcery.com/phplogic.htm>
In basic terms, if you use a logic mask with a byte (being 8-bits) then
you should be able to mask out what you need. For the first five bits
(reading from left to right below) you'd then use the mask consisting of
the first five numbers below added together;
7 6 5 4 3 2 1 0 Byte position
128 + 64 + 32 + 16 + 8 + 4 + 2 + 1 Value
result = <byte we're working on> AND <mask>
$result = $byte and 248
Look up 'bitwise operations' for further help.
<http://www.litfuel.net/tutorials/bitwise.htm>
HTH?
--
"This week I have mostly been listening to -
The Film Music of Alan Rawsthorne and British Film Music Volumes I & II.
[Back to original message]
|