简体   繁体   English

是否可以仅在 python 上使用左移、异或和按位运算对 16 位数字进行位反转

[英]Is it possible to do bit reversal for a 16 bit number only using shift left, xor, and bitwise operations on python

I was wondering if it is possible to do bit reversal for a 16bit binary number such as 1000000000000011 to 1100000000000001 by only using the shift left >>, Xor ^, And & functions on python?我想知道是否可以仅通过在 python 上使用左移 >>、Xor ^ 和 & 函数对 16 位二进制数(例如 1000000000000011 到 1100000000000001)进行位反转? Adding and subtracting binary can also be used for this problem加减二进制也可以用来解决这个问题

The description you give in the comments for "left shift" is not what Python does for << - you're describing what would be called a "left rotate".您在评论中对“左移”的描述不是 Python 对<<所做的 - 您描述的是所谓的“左旋转”。 Since Python doesn't provide that, let's code it up quick:由于 Python 不提供,让我们快速编写代码:

def circular_shift_16(x, n):
    assert(0 <= x <= 0xffff)
    return (( x << n) & 0xffff) | (x >> (16-n))

With that as a building block, you can do the bit reversal.以此为基础,您可以进行位反转。

def bit_reversal_16(x):
    # reverse single bit pairs
    x = (circular_shift_16(x, 15) & 0x5555) ^ (circular_shift_16(x, 1) & 0xaaaa)
    # reverse groups of 2
    x = (circular_shift_16(x, 14) & 0x3333) ^ (circular_shift_16(x, 2) & 0xcccc)
    # reverse groups of 4
    x = (circular_shift_16(x, 12) & 0x0f0f) ^ (circular_shift_16(x, 4) & 0xf0f0)
    # reverse groups of 8
    x = circular_shift_16(x, 8)
    return x

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM