Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation
 
PerlMonks  

Re: 5x6-bit values into/out of a 32-bit word

by grinder (Bishop)
on Mar 18, 2007 at 09:22 UTC ( #605340=note: print w/ replies, xml ) Need Help??


in reply to 5x6-bit values into/out of a 32-bit word

I'd do it this way. Encapsulate and abstractulate as appropriate:

my $num = shift; my $bits = 6; my $mask = (1 << $bits) - 1; my @out = map { ($num & $mask << $_ * $bits) >> $_ * $bits } 0..$bits-1;

update: oops, the map 0 .. $bits-1 is just a fortunate accident of 5 == 6-1. The following is better:

my $num = shift; my $groups = 5; my $bits = 6; my $mask = (1 << $bits) - 1; my @out = map { ($num & $mask << $_ * $bits) >> $_ * $bits } 0..$groups-1;

2nd update: oh, and you want to go back the other way. That's even easier:

my @in = (30, 14, 27, 2, 17); my $width = 6; my $offset = 0; my $out = 0; $out |= ($_ << ($offset++ * $width)) for @in;

• another intruder with the mooring in the heart of the Perl


Comment on Re: 5x6-bit values into/out of a 32-bit word
Select or Download Code

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://605340]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others romping around the Monastery: (12)
As of 2015-07-06 17:24 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (77 votes), past polls