簡體   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

我想知道是否可以僅通過在 python 上使用左移 >>、Xor ^ 和 & 函數對 16 位二進制數(例如 1000000000000011 到 1100000000000001)進行位反轉? 加減二進制也可以用來解決這個問題

您在評論中對“左移”的描述不是 Python 對<<所做的 - 您描述的是所謂的“左旋轉”。 由於 Python 不提供,讓我們快速編寫代碼:

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

以此為基礎,您可以進行位反轉。

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