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

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.