【问题标题】:Rewrite C++ bitshift operator in Python在 Python 中重写 C++ 位移运算符
【发布时间】:2020-12-16 11:37:16
【问题描述】:

我在 C++ 中有这段代码:

#include <iostream>

using namespace std;

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

    return 0;
}

当我执行它时,它给我的结果是 192。 但是当我在 Python 中做同样的事情 (23

【问题讨论】:

    标签: python c++ shift


    【解决方案1】:

    23 &lt;&lt; 6 在 C++ 中作为 int 执行,但将其分配回 unsigned char 会将其截断为其位大小(在 Python 运行的任何平台上为 8)。因此,要在 Python 中获得相同的值,您必须执行 (23 &lt;&lt; 6) &amp; 0xFF

    另一方面,要在 C++ 中获得“正确”(非截断)结果,只需将其分配给 unsigned int 而不是 unsigned char(如果 int 足够大,则此方法有效,否则你必须先将一个操作数转换为更大的值;Python 没有这样的问题,因为它使用任意大小的整数。

    【讨论】:

    • 哦,是的。非常感谢你。那就是我一直在寻找的东西。 :)
    猜你喜欢
    • 2017-07-12
    • 2011-02-02
    • 1970-01-01
    • 1970-01-01
    • 2014-11-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-09
    相关资源
    最近更新 更多