in reply to Extracting Bit Fields (Again)
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
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Extracting Bit Fields (Again)
by oyster2011 (Initiate) on Dec 22, 2011 at 05:23 UTC | |
by BrowserUk (Patriarch) on Dec 22, 2011 at 08:35 UTC | |
by oyster2011 (Initiate) on Jan 02, 2012 at 06:22 UTC | |
by BrowserUk (Patriarch) on Jan 02, 2012 at 07:10 UTC | |
by oyster2011 (Initiate) on Jan 02, 2012 at 08:09 UTC |