Warm tip: This article is reproduced from serverfault.com, please click

Rewrite C++ bitshift operator in Python

发布于 2020-12-16 11:37:16

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?

Questioner
westman379
Viewed
0
Matteo Italia 2020-12-16 19:42:05

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).