Perl has the same type of bitwise shift operators that 'C' does.

There is no need to fiddle around with some intermediate hex form, just operate on the int like you would in 'C'. My MSbit() below returns power of 2 bit position for the int that was supplied. The left shift and right shift operators work just like you would expect in C.

Use the printf ("%x") or ("%X") descriptor as you wish to print the values.

#!/usr/bin/perl -w use strict; print "power of 2 bit of 1 is: ",MSbit(1),"\n"; #prints 0 print "power of 2 bit of 8 is: ",MSbit(8),"\n"; #prints 3 my $num = 256; print "power of 2 bit of $num is: ",MSbit($num),"\n"; #prints 8 $num = $num << 1; print "power of 2 bit of $num is: ",MSbit($num),"\n"; #prints 9 $num = 254; print "power of 2 bit of $num is: ",MSbit($num),"\n"; #prints 7 $num = $num << 1; print "power of 2 bit of $num is: ",MSbit($num),"\n"; #prints 8 #Most Significant bit numbering is like #...9876543210 # sub MSbit ##returns power of 2 of MS bit { my $num = shift; die "illegal value in MSbit" if $num == 0; my $bit =-1; while ($num != 0) { $num = $num >> 1; $bit++; } return $bit; } __END__ output of above is: power of 2 bit of 1 is: 0 power of 2 bit of 8 is: 3 power of 2 bit of 256 is: 8 power of 2 bit of 512 is: 9 power of 2 bit of 254 is: 7 power of 2 bit of 508 is: 8
Update:

yes, just like $n = $n +2; can be replaced by $n +=2;, $num = $num >> 1 can be replaced by $num >>= 1; this is also fine. I would also add that if you have a 128 bit, 64 bit, 32 bit, 16 bit machine the above algorithm will work.


In reply to Re: Decimal to Hexadecimal conversion and extraction MSB by Marshall
in thread Decimal to Hexadecimal conversion and extraction MSB by Anonymous Monk

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • 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:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.