In the system example, you have a 16 bit integer which holds three values. One value is the 15th bit, one is bits 14-8, and the last is 7-0. In order to extract those values, the common way to do this is to shift over the appropriate number of bits, then mask off the unneeded bits.

For an example, let's use the field 1100 0001 0000 1111. The first value is a 1, the second is 100 0001, and the third is 0000 1111.

To get the first value, shift to the right 15 bits, then AND that with 1. What's really happening is you are ANDing it with a bunch of leading zeros, and then a final one. So in this case, ANDing a one with a one yields one.

It's more interesting (and it makes the reason for the ANDing more apparent) when getting the second value. You right shift 8 bits, ending up with (with leading zeros) 0000 0000 1100 0001. If you were to then get this value, you would end up with 193. The problem here is that we only want the first 7 bits, but we've got that 8th bit in there. So we zero out the high bits by ANDing it with 0111 1111. This results in 0100 0001, or 65.


In reply to Re^3: Shift Operators And Bitwise Operators by lostjimmy
in thread Shift Operators And Bitwise Operators by biohisham

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.