Extraction of bits using unpack

P

pip

Hi all,

I am trying to extract some data from a binary file using unpack. All
is well where I have to extract simple data types such as shorts,
strings and ints but then I reach this in the docs I am using:

Here is the way a date is represented:

MSB LSB
__________________________________________________________
| year | Month | Day | Time |
| 12 bits | 4 bits | 5 bits | 11 bits |
|__________|____________|___________|____________________|

I have played with the hex string operator in unpack with little
joy. I also had a go at it with vec() but got nowhere.

Could someone please point me in the right direction for extracting
this data please?

Thanks,

pip

P.S if it makes a difference I am pulling the file from an x86 based
system and parsing it on an x86 system.
 
A

Anno Siegel

pip said:
Hi all,

I am trying to extract some data from a binary file using unpack. All
is well where I have to extract simple data types such as shorts,
strings and ints but then I reach this in the docs I am using:

Here is the way a date is represented:

MSB LSB
__________________________________________________________
| year | Month | Day | Time |
| 12 bits | 4 bits | 5 bits | 11 bits |
|__________|____________|___________|____________________|

I have played with the hex string operator in unpack with little
joy. I also had a go at it with vec() but got nowhere.

Could someone please point me in the right direction for extracting
this data please?

You want the usual shifting and masking of integers, it seems. Get
the four bytes into an integer $x (unpack), and apply

my( $year, $month, $day, $time) = bit_split( $x, 12, 4, 5, 11);

with

sub bit_split {
my $bits = shift;
my @parts;
for ( reverse @_ ) {
my $mask = ( 1 << $_) - 1;
unshift @parts, $mask & $bits;
$bits >>= $_;
}
@parts;
}

Anno
 
P

pip

Anno,
pip said:
Hi all,

I am trying to extract some data from a binary file using unpack. All
is well where I have to extract simple data types such as shorts,
strings and ints but then I reach this in the docs I am using:
[ ... snip ... ]

my( $year, $month, $day, $time) = bit_split( $x, 12, 4, 5, 11);

with

sub bit_split {
my $bits = shift;
my @parts;
for ( reverse @_ ) {
my $mask = ( 1 << $_) - 1;
unshift @parts, $mask & $bits;
$bits >>= $_;
}
@parts;
}

This worked a charm, I would never have worked this out without your
help. Now to go a read up on this bit shifting malarkey.

Cheers,

pip
 

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,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top