0

What's the meaning of binary(number >> 1), and how does it work in the following code? Could somebody explain it to me in detail? Thank you!

#include <iostream.h>

void binary(int);

int main() {
    int number = 3;
    cout << number << endl;
    binary(number);
}

void binary(int number) {
    if(number <= 1) {
        cout << number;
        return;
    }
    int remainder = number%2;
    binary(number >> 1);  //How does this work exactly?   
    cout << remainder;
}
Z_J
  • 125
  • 1
  • 11
  • 2
    You mean `>>` ? It´s a "right shift". And because you called it "insertion expression", don´t confuse it´s purpose with streams stuff like cin/cout. It´s the same symbol, but these stream classes are doing something completely different with their overloaded operators. – deviantfan Mar 09 '15 at 01:01
  • 1
    http://en.wikipedia.org/wiki/Bitwise_operation#Shifts_in_C.2C_C.2B.2B.2C_C.23.2C_Python – drescherjm Mar 09 '15 at 01:01
  • 1
    http://stackoverflow.com/a/6385887/487892 – drescherjm Mar 09 '15 at 01:03
  • 2
    BTW don't use `%2` to get the low bit, use `&1`. `%` does the wrong thing for negative numbers. – Ben Voigt Mar 09 '15 at 01:05
  • @BenVoigt His function returns before then if given a negative number –  Mar 09 '15 at 01:10
  • 2
    You can find out the menaning of basic operators etc. by looking them up. E.g. (http://en.cppreference.com/w/cpp/language/operator_arithmetic). The recursive call is more involved, for that you'd better run your program in a debugger, and step trough it statement by statement. Do not ethat `void main` is non-standard, and that `` is a pre-standard header (before 1998), not usually available with modern compilers. – Cheers and hth. - Alf Mar 09 '15 at 01:13
  • @deviantfan Thank you so much! Yes I misunderstood it as an insertion/extraction operator. I think I get it now. – Z_J Mar 09 '15 at 01:19

1 Answers1

2

The << and >> operators are bit-shift operators; they change the value based off of the binary representation of the number; an example will clarify:

001010 (10)

If we do << 1 (left shift 1 bit), then we get:

010100 (20)

If you noticed, the above is equivalent to multiplying by two; in fact, shifting left n bits is equivalent to multiplying by 2 to the nth power!

If we do >> 1 (right shift 1 bit) to the original, we get this:

000101 (5)

Again, if you look carefully, you'll notice the above is equivalent to dividing by 2! In fact, the right shift operator is the inverse operator of the left shift operator, so right shifting n bits is equivalent to dividing by 2 to the nth power!

Also, void main() is just plain wrong, so don't use it. <iostream.h> should be replaced by <iostream> as the former was used prior to standard ISO C++.