cheers brothers and sisters,
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:
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
}
The code basically:
gets an integer as argument
converts it to a binary
takes the 3 last (MSB) bits from it as a binary
calculates the integer value of that binary
Thanks..
--
to ask a question is a moment of shame
to remain ignorant is a lifelong shame
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.