insaniac has asked for the wisdom of the Perl Monks concerning the following question:
I have this sub to calculate the 3 most significant bits based on an integer. The integer I get is the integer value of the TOS byte, a value which is retreived over SNMP. I have to find the TOS Precedence, and that is the sum of the 3 MSBs.
The sub I have works, but laziness seems to strike everyone eventually, I was wondering if there are easier or better ways to do it? I'm just always curious about how someone else would do it ;-)
The code basically:sub calc_tosprecedence { my $int_val = shift; my $bit = 7; my @b = (0,0,0,0,0,0,0,0); while ($int_val > 0 ) { $rest = 1 if $int_val - 2**$bit >= 0 ; $rest = 0 if $int_val - 2**$bit < 0 ; $int_val = $int_val - 2**$bit if $rest; $b[$bit-- ] = $rest; } @b = reverse @b; my @prec = @b[0 .. 2]; $sum = 0; @prec = reverse @prec; $sum += $prec[$_] * 2**$_ for (0 .. $#prec); return $sum }
Thanks..
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: calculating the 3 MSBs from an integer
by borisz (Canon) on Feb 17, 2005 at 13:00 UTC | |
by Random_Walk (Prior) on Feb 17, 2005 at 14:05 UTC | |
by borisz (Canon) on Feb 17, 2005 at 14:13 UTC | |
by insaniac (Friar) on Feb 17, 2005 at 14:40 UTC | |
by Random_Walk (Prior) on Feb 17, 2005 at 15:27 UTC | |
by insaniac (Friar) on Feb 17, 2005 at 21:14 UTC | |
| |
by insaniac (Friar) on Feb 17, 2005 at 13:03 UTC | |
|
Re: calculating the 3 MSBs from an integer
by spurperl (Priest) on Feb 18, 2005 at 10:26 UTC | |
by insaniac (Friar) on Feb 18, 2005 at 11:57 UTC |