Here is one way to do it (but you aren't going to like it!):
print unpack 'C*', pack '(B8)*', map{ substr '00000000'.$_, -8 } unpack 'A1A3A4',unpack 'B*',pack 'C', 162;; 1 2 2
To explain that, (right-to-left):
## pack 162 into an 8-bit binary value (a char). pack 'C', 162 ## unpack that into it's bits, (asciized binary bitstring). unpack 'B*', ## split that into the 3 fields. ('1','010', '0010' ). unpack 'A1A3A4', ## Pad each to the smallest size (8 bits) that Perl can deal with nume +rically. map{ substr '00000000'.$_, -8 } ## Pack them back up to binary values (chars). pack '(B8)*', ## And unpack them back to numeric values. unpack 'C*', ## and convert those to ascii-decimal for display print
The problem with vec is that it only allows you to deal with bits in quantites that are powers of 2, and on powers of two boundaries, which makes dealing with your 3-bit field problematic.
Probably easier to use is a subroutine like this:
#! perl -slw use strict; sub bitField { my( $value, $offset, $size ) = @_; my $mask = ( ( 1<<$size) - 1 ) << $offset; return ( $value & $mask ) >> $offset; } print bitField 162, 7, 1; print bitField 162, 4, 3; print bitField 162, 0, 4; __END__ P:\test>499354 1 2 2
In reply to Re: Extracting Bit Fields (Again)
by BrowserUk
in thread Extracting Bit Fields (Again)
by ozboomer
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |