in reply to Re^2: Extracting Bit Fields (Again)
in thread Extracting Bit Fields (Again)
Maybe something like this would work for you? (Update: simplified code):
Update 2: Unsimplified code to correct errors noted by oyster2011 below (Thanks!):
#! perl -slw use strict; sub bitFields{ my( $val, $pat ) = @_; my @fields = unpack $pat, reverse unpack 'b32', pack 'L', $val; return unpack 'L*', pack '(b32)*', map scalar( reverse), @fields; } my( $linkStatus, $cardStatus, $reserved, $intrStatus ) = bitFields( 123456789, 'x2 a2 a3 a7 a15' ); print for $linkStatus, $cardStatus, $reserved, $intrStatus; __END__ C:\test>bitFields.pl 0 3 86 31138
Use 'xn' in the template to skip over bits you aren't interested in. You might need to use 'B32' instead of 'b32' depending upon your platform.
Masking and shifting is almost certainly quicker, but this could be seen as a nice abstraction.
You could also do away with the intermediates if that floats your boat:
sub bitFields{ unpack 'L*', pack'(b32)*', map scalar( reverse), unpack $_[1], reverse unpack 'b32', pack 'L', $_[0]; }
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^4: Extracting Bit Fields (Again)
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 |