Problem For a byte of data, swap its high and low bits one by one. For example, 11010001, after swapping the corresponding bits 0-7, 1-6, 2-5, 3-4, it becomes 10001011. 【Paid】 STM32 Embedded Resource Package
Solution Approach
For this problem, the first thought is to process the original byte bit by bit using shift operations, utilizing another variable to store the swapped result. This solution is clear in thought and should not be difficult to code. Below is the code corresponding to this approach:
unsigned char shift_fun1(unsigned char data) { unsigned char i; unsigned char tmp=0x00; for(i=0;i<8;i++) { tmp=((data>>i)&0x01)|tmp; if(i<7) tmp=tmp<<1; } printf(" after shift fun1 data=%x \n",tmp); return tmp; }
The above code is not difficult to implement, and it is quite efficient. However, there are more concise solutions. In embedded development, the butterfly exchange method and lookup table method are commonly used to solve byte swapping issues. The lookup table method, as the name suggests, involves storing some values in memory, which can be referenced when needed, but it does consume additional storage space. Here, we will mainly introduce the butterfly exchange method. The butterfly exchange works as follows:
data=(data<<4)|(data>>4); data=((data<<2)&0xcc)|((data>>2)&0x33); data=((data<<1)&0xaa)|((data>>1)&0x55);
We can perform an execution calculation:Assuming the original bit sequence is 0 1 0 1 1 0 0 1After executing data=(data<<4)|(data>>4); the sequence becomes 1 0 0 1 0 1 0 1After executing data=((data<<2)&0xcc)|((data>>2)&0x33); the sequence becomes 0 1 1 0 0 1 0 1After executing data=((data<<1)&0xaa)|((data>>1)&0x55); the sequence becomes 1 0 0 1 1 0 1 0 More abstractly, the original bits are 1 2 3 4 5 6 7 8. After executing data=(data<<4)|(data>>4); the bit sequence becomes 5 6 7 8 1 2 3 4After executing data=((data<<2)&0xcc)|((data>>2)&0x33); the bit sequence becomes 7 8 5 6 3 4 1 2After executing data=((data<<1)&0xaa)|((data>>1)&0x55); the bit sequence becomes 8 7 6 5 4 3 2 1 Thus, the entire bit reversal is completed. Below is the specific implementation code:
unsigned char shift_fun2(unsigned char data) { data=(data<<4)|(data>>4); data=((data<<2)&0xcc)|((data>>2)&0x33); data=((data<<1)&0xaa)|((data>>1)&0x55); printf(" after shift fun2 data=%x \n",data); return data; }