in reply to Decimal to Hexadecimal conversion and extraction MSB

Oh, I see now that what you want to implement is a virtual register with an arbitrary number of bits. The width of the register is defined by the left most bit of the input number. Then you want to do a left shift by one bit.

That is quite frankly a VERY strange requirement and I missed this strange specification on my first attempt. Your spec:

C 7654 3210 1110 1111 = 0xEF = decimal 239 1 1101 1110 left shift one showing carry 1101 1110 result without carry = 0xDE = 222
But this is possible! Recyling my MSbit() code I get your desired output of 222 from your input of 239.

BUT there has to be something wrong in terms of the specification! Basically as you have seen, there are many ways to implement bit operations in Perl. What you are asking for is so very strange, I can't believe that it is right. Please reformulate your question with a very clear set of input and output values. If you are dealing with 8 bit values, then the code becomes a lot easier!

#!/usr/bin/perl -w use strict; my $input = 0xEF; my $andMask = (2**(MSbit($input)+1))-1; printf ("%X\n", ($input<<1) & $andMask); ## prints DE sub MSbit ##returns power of 2 of MS bit { my $num = shift; my $bit =-1; while ($num != 0) { $num = $num >> 1; $bit++; } return $bit; }
If you just want a virtual 8 bit register:

#!/usr/bin/perl -w use strict; my $input = 0xEF; #this is 239 in decimal my $mask = 0xFF; printf ("%X\n", $input<<1 & $mask); # prints DE which means 222 in decimal
If you mean just an 8 bit virtual register, here is the one line version:
printf ("%X\n", 0xEF<<1 & 0xFF); # prints DE which means 222 in decimal
And yes, printf ("%X\n", 239<<1 & 0xFF); #will do the same thing!