Bridget Benson wrote:
> 
> This is a response to last week's question on how to extract bits out
> of a string of bytes.
> 
> Assume $packet is a string of 8 bytes.
> 
> To extract the second byte:
> $second = unpack ('C', substr($packet, 1, 1));

You really don't need substr() here.

$second = unpack 'x C', $packet;


> To extract the last four bytes
> $last_four = unpack ('N', substr($packet, 4, 4));

Or here.

$last_four = unpack 'x4 N', $packet;


> To extract the first two:
> $first_two = unpack ('n', substr($packet, 0, 2));

Or here.

$first_two = unpack 'n', $packet;


> To extract the first four bits from the second byte:
> $first_four_bits = int (unpack ('C', substr($packet, 1, 1)) / 16);

And, you can use vec() to extract bits.

$first_four_bits = vec $packet, 2, 4;


> To extract the second four bits from the second byte:
> $second_four_bits = (unpack ('C', substr($packet, 1, 1)) % 16);

$second_four_bits = vec $packet, 3, 4;



:-)

John
-- 
use Perl;
program
fulfillment

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]

Reply via email to