in reply to Decimal to Hexadecimal conversion and extraction MSB

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.