V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
just1
V2EX  ›  Python

无符号位运算怎么实现

  •  
  •   just1 · 2015-11-14 21:59:40 +08:00 · 2407 次点击
    这是一个创建于 3107 天前的主题,其中的信息可能已经有所发展或是发生改变。
    如题 TAT
    6 条回复    2015-11-16 11:17:33 +08:00
    Valyrian
        1
    Valyrian  
       2015-11-14 23:04:48 +08:00
    & | ^ << >> 这五个
    不过没人拿 python 干这个,因为 python 的 int 长度不固定
    just1
        2
    just1  
    OP
       2015-11-14 23:18:49 +08:00 via Android
    @Valyrian 蛤,什么意思
    imn1
        3
    imn1  
       2015-11-14 23:23:59 +08:00
    自己看手册位运算相关说明
    无符号指不区分正负,但实际上 python 取反还是会变负,也就是说有固定位长
    ming2281
        4
    ming2281  
       2015-11-15 12:00:24 +08:00
    这种还是拿 C/C++之类的吧
    Python 搞这个不是很好,bug 多
    CRVV
        5
    CRVV  
       2015-11-15 15:49:13 +08:00   ❤️ 2
    @imn1 @ming2281

    Python 里,~ 运算符的定义是 -(x+1)
    << 和 >> 运算符的定义是乘或除以 2 的若干次幂
    其它 3 个 & | ^ 和有没有符号无关,正数和负数只是表示了不同的值而已

    这种事情看一下文档就知道了,别随意“也就是说”,也别随意说“ bug 多”

    https://docs.python.org/3/reference/expressions.html#unary-arithmetic-and-bitwise-operations
    ming2281
        6
    ming2281  
       2015-11-16 11:17:33 +08:00
    @CRVV 语言还是充满这歧义. 我说的是「拿 Python 做这件事会出现 bug 」,不是说「 Python 本身的 bug 多」,一个语言基础性的东西都 bug 多, 谁还会用?

    举一例: 数一个数中 1 的个数
    最容易想到的办法是:
    int countOne(const int num)
    {
    int count = 0;
    int flag = 1;

    while (flag != 0) {
    if ((flag & num) != 0) {
    count++;
    }
    flag <<= 1;
    }
    return count;
    }
    次容易想到的是
    int countOne(const int num)
    {
    int count = 0;
    unsigned int flag = 0x80000000;

    while (flag != 0) {
    if ((flag & num) != 0) {
    count++;
    }
    flag >>= 1;
    }
    return count;
    }
    有点技巧性的
    int countOne(int num)
    {
    int count = 0;

    while (num != 0) {
    count++;
    num = num & (num - 1);
    }
    return count;
    }

    其中在 Python 中不能翻译最容易想到的那个, 因为往左移会无限拓展. 这就是「有的时候用 Python 搞位运算的东西会出现与自己判断不相符合的情况」,我没有说「 Python 的 bug 多」
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   1971 人在线   最高记录 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 16:21 · PVG 00:21 · LAX 09:21 · JFK 12:21
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.