westman379
westman379

Reputation: 713

Rewrite C++ bitshift operator in Python

I have this code in C++:

#include <iostream>

using namespace std;

int main()
{
    unsigned char v1;
    v1 = 23 << 6;
    cout << "v1: " << (int)v1;

    return 0;
}

When I execute it, it gives me result of 192. But when I do the same (23 << 6) in Python I get 1472 instead of 192. What am I doing wrong here? Do you know any method to rewrite this bitshift operation 1:1 to Python?

Upvotes: 2

Views: 121

Answers (1)

Matteo Italia
Matteo Italia

Reputation: 126867

23 << 6 is performed as an int in C++, but assigning it back to an unsigned char truncates it to its bits size (8 on any platform where Python runs). So, to obtain the same value in Python you have to do (23 << 6) & 0xFF.

On the other hand, to obtain the "correct" (non-truncated) result in C++ just assign it to an unsigned int instead of an unsigned char (this works if int is big enough for the result, otherwise you have to cast one operand to something bigger first; Python doesn't have such problems as it uses arbitrary size integers).

Upvotes: 4

Related Questions