pack/unpack bits

A

Aaron Brice

I have a problem with using unpack to separate out some arbitrary bits
from some binary data received using some wacky protocol. The first bit
of the binary message is the "rbit", the next 15 bits is the device id,
etc. What I'd like to use is unpack() to map the bits to various
variables such as:

#!/usr/bin/perl

$msg = pack ("H*", "8000ffff");

($rbit, $dev, $buffer) = unpack("B1B15B*", $msg);

print "rbit: $rbit\n";
print "devid: $devid\n";
print "buffer: $buffer\n";

I would expect this to have rbit set to 1, devid set to 000000000000000,
and buffer set to 1111111111111111. Instead, the result is:

rbit: 1
devid: 000000001111111
buffer: 11111111

It seems like the "B1" token in the unpack template reads a whole byte and
gives the first bit of it, the B15 token reads the next two bytes and
gives the first 15 bits of them, and B* gets the rest, which is only one
byte left. There's a lot of missing bits there! Is there a way for me to
use unpack() to do what I want without having to use a more awkward
masking and shifting sytem?

Thanks,
Aaron
 
K

Kien Ha

Aaron said:
I have a problem with using unpack to separate out some arbitrary bits
from some binary data received using some wacky protocol. The first bit
of the binary message is the "rbit", the next 15 bits is the device id,
etc. What I'd like to use is unpack() to map the bits to various
variables such as:

#!/usr/bin/perl

$msg = pack ("H*", "8000ffff");

($rbit, $dev, $buffer) = unpack("B1B15B*", $msg);

print "rbit: $rbit\n";
print "devid: $devid\n";
print "buffer: $buffer\n";

I would expect this to have rbit set to 1, devid set to 000000000000000,
and buffer set to 1111111111111111. Instead, the result is:

($rbit, $dev, $buffer) = unpack "A1A15A*", unpack "B*", $msg;
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top