First of all, in Perl, your "$decimal_number" is internally stored in binary representation anyway.
Your number is converted from the decimal literal "254" in your program text into binary when your program is compiled, and it is converted back to decimal every time you "print" the variable "$decimal_number" (actually, Perl caches the resulting string).
Next, in two's complement binary representation, the MSB is the sign of the number. Since "254" is positive, you know that the MSB is 0. When a number is negative, you know that its MSB is 1.
But this is probably not what you mean; from your example I deduce that you want the MSB of your decimal number in 8 bit representation.
There are various solutions to this problem (as always in Perl, TIMTOWTDI ;-)). The simplest way is by using a mask, such as 0x80 (for 8 bits; for 16 bit numbers it would be 0x8000):
$msb = $decimal_number & 0x80;Another solution (a bit of overkill here, though!) would go as follows:
use Bit::Vector; $v = Bit::Vector->new(8); # 8 bits $v->from_Dec($decimal_number); $msb = $v->MSB();
Hope this helps! :-)
In reply to Re: Decimal to Hexadecimal conversion and extraction MSB
by stbey
in thread Decimal to Hexadecimal conversion and extraction MSB
by Anonymous Monk
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |