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? 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". Since Python doesn't provide that, let's code it up quick:
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.