The binary (16-bit) reverse order is required to be calculated. For example, the number 12345 is represented in binary:
00110000 00111001
In reverse order, we get a new binary number:
10011100 00001100
The easiest way to think of it is to exchange the data at both ends in sequence and traverse the number from the right to the left. When I bit encounters 1, set the (17-i) Bit corresponding to the backward number to 1.
def reverseBinary(num): print bin(num) new=0 tmp=(1<<15) for i in xrange(16): if num&1: new|=tmp tmp>>=1 num>>=1 return new if __name__==‘__main__‘: print bin(reverseBinary(12345))>>> 0b00110000001110010b1001110000001100
There is also a high/low bit swapping method similar to the merge sort method.
Imagine the reverse order 'AB', Which is 'ba '.
In reverse order, ABCD can be first exchanged as cdab and then one-to-one switched to dcba.
In reverse order abcdefgh, efghabcd is exchanged for four or four, fehgcdab is exchanged for two, and efghdcaba is exchanged one by one.
Then it can be extended to binary representation:
Step 1: Each two digits is a group, and the high and low bits in the group are exchanged.
00 11 00 00 00 11 10 01
--> 00 11 00 00 00 11 01 10
Step 2: Each 4 bits are a group, with high/low bits in the Group exchanged
0011 0000 0011 0110
--> 1100 0000 1100 1001
Step 3: Every 8 bits are a group, with high/low bits in the Group exchanged
11000000 11001001
--> 00001100 10011100
Step 4: Each 16 bits are a group, with high/low bits in the Group exchanged
0000110010011100
--> 1001110000001100
When the high/low bits are swapped, the operation is probably to shift the even bits to the left by 1 bits, and the odd bits to the right by 1 bits.
Original number 00110000 00111001
Odd digit 0_1_0_0 _ 0_1_1_0 _
Even bits _ 0_1_0_0 _ 0_1_0_1
Fill the remaining digits with 0, and then shift the odd digits one to the right, and the even digits one to the left. Then, perform bitwise AND operations on the two data, that is, the data exchange effect on the parity bit can be achieved:
def reverseBinary(a): a = ((a & 0xAAAA) >> 1) | ((a & 0x5555) << 1) a = ((a & 0xCCCC) >> 2) | ((a & 0x3333) << 2) a = ((a & 0xF0F0) >> 4) | ((a & 0x0F0F) << 4) a = ((a & 0xFF00) >> 8) | ((a & 0x00FF) << 8) return aif __name__==‘__main__‘: print bin(reverseBinary(12345))