What is the >> maths operator in C++

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • DonMatteo
    New Member
    • Mar 2008
    • 5

    #1

    What is the >> maths operator in C++

    Hi there,

    I have a code with the following line:
    long s = (ib-ia) >> 2

    and I dont know what it means. When I debug it seems that the >> operator is used as a divide operator. What is exactly this operator >> in terms of mathematics?

    Thanks,

    Matteo
  • Ganon11
    Recognized Expert Specialist
    • Oct 2006
    • 3651

    #2
    The >> operator is not strictly a mathematical operator - it is the right shift operator. Basically, any value is stored as a series of bits in C/C++ (or any other programming language). So if you have the number 23, your computer might store it as:

    0001 1001

    which is binary for 23.

    Now, if I were to shift all the bits in the binary number to the right, I'd get a new number. Let's shift them to the right twice: the bit pattern is then:

    0000 0110

    which is 6. This is precisely what the >> operator does. The << operator is similar, but shifts in the left direction.

    It just so happens that when you perform a shift operation:

    Code:
    a >> b;
    // or
    c << d;
    these are the same as calculating a / (2**b) and c * (2**d), where ** means 'to the power of'.

    Comment

    Working...