推荐学习书目
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
luckyc
V2EX  ›  Python

用 Python 重写 Java 代码同样的位移取反操作, 遇到问题, 请帮忙看看

  •  
  •   luckyc · Sep 16, 2021 · 1803 views
    This topic created in 1700 days ago, the information mentioned may be changed or developed.
    inputStream = new DataInputStream(new BufferedInputStream(new FileInputStream(srcFile), 1024 * 8));
                byte[] vb = new byte[7];
    
                if (inputStream.read(vb, 0, 6) > 0) {
                    for (int i = 0; i < 6; i++) {
                        vb[i] = (byte) ((0xFF & vb[i]) >> 4 | (0xFF & vb[i]) << 4);
                        vb[i] = (byte) ~vb[i];
                    }
                    vb[6] = 0;
                }
    
                version = new String(vb, 0, vb.length - 1);
    
    def decode():
        version_byte = b'\x9a\xac\x1d\xfc\xfc\xfc'
        result_bytes = bytearray()
    
        for i, value in enumerate(version_byte):
            version_int = value
            version_int = (version_int >> 4 | version_int << 4)
            version_int = ~version_int
            print(f'{version_int} {version_int}')
            result_bytes.insert(i, version_int)
    
    

    帮忙看看 java 的代码, 我用 python 实现不了同样的功能

    3 replies    2021-09-16 22:16:13 +08:00
    2i2Re2PLMaDnghL
        1
    2i2Re2PLMaDnghL  
       Sep 16, 2021   ❤️ 1
    int 和 byte 的区别,Python 我记得应该是没有 byte 类型?至少 bytes.__getitem__ 出来的是 int
    version << 4 会超过 byte 范围,做一下 (...)%256
    ~version 会变负的,方便点就是 255-version,正规点就是 (~version)%256
    ruanimal
        2
    ruanimal  
       Sep 16, 2021   ❤️ 1
    处理下溢出
    wangxn
        3
    wangxn  
       Sep 16, 2021   ❤️ 1
    需要对位操作的结果作截断避免溢出:
    ```
    def decode():
    version_byte = b'\x9a\xac\x1d\xfc\xfc\xfc'
    result_bytes = bytearray()

    for i, value in enumerate(version_byte):
    version_int = value
    version_int = (version_int >> 4 | version_int << 4) & 0xff
    version_int = (~version_int) & 0xff
    print(f'{version_int} {version_int}')
    result_bytes.insert(i, version_int)
    ```
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   3218 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 99ms · UTC 14:36 · PVG 22:36 · LAX 07:36 · JFK 10:36
    ♥ Do have faith in what you're doing.