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]; }
In reply to Re^3: Extracting Bit Fields (Again)
by BrowserUk
in thread Extracting Bit Fields (Again)
by ozboomer
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |