//2. Use macros to exchange odd and even bits in a binary number. #include<stdio.h> #include<stdlib.h> #define EXH(x) \ ((x & 0x5555555

//2. Use macros to exchange odd and even bits in a binary number.

Analysis: Extract the even digits: Let the original number be bitwise and 01010101010101010101010101010101, the hexadecimal form is 0x55555555

            Extract odd digits: the original number is bitwise and 10101010101010101010101010101010, the hexadecimal form is 0xaaaaaaaa

                                 Even-numbered bits are shifted one bit to the left, odd-numbered bits are shifted one bit to the right, the two are bitwise ORed, remember to the target number

#include<stdio.h>
#include<stdlib.h>
#define EXH(x) \
((x & 0x55555555) << 1) | ((x & 0xaaaaaaaa) >> 1)


int main()
{
int a = 10;
int ret = EXH(a);
printf("%d\n", ret);
system("pause");
return 0;
}

Guess you like

Origin blog.csdn.net/lxp_mujinhuakai/article/details/54378956