1

why the result of C++ and python bitwise shift operator are diffrernt?
python

>>> 1<<20
1048576

C++

cout <<1<<20;
120
3
  • 11
    cout << (1<<20);. You're not bit shifting, you're just sending '1' and '20' to cout. You're mixing the output operator and the bit shift operator. Commented Aug 14, 2020 at 15:44
  • 1
    In C++ you'd want this: cout << (1<<20);. C++ is a context sensitive language. The same symbols mean different things in different contexts (and can even be overloaded to gain entirely new, user-defined, meaning) Commented Aug 14, 2020 at 15:45
  • 3
    Note that (1 << 20) is UB in C++ for a 16 bit int. Commented Aug 14, 2020 at 15:52

2 Answers 2

5

The result differes because of the operator associativity in C++.

std::cout << 1 << 20;

is the same as

(std::cout << 1) << 20;

because operator << is left-associative. What you intend to do is

std::cout << (1 << 20);
Sign up to request clarification or add additional context in comments.

Comments

1

cout overloads the '<<' operator to print the values. So when you are doing

cout <<1<<20;

It actually prints 1 and 20 and doesnt do any shifting

int shifted = 1 << 20;
cout << shifted;

This should return the same output as python's

simpler way is to do

cout << (1 <<20);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.