高低位翻转函数(1、2、4、8字节)
1 #include <stdio.h> 2 3 typedef unsigned char uint8_t; 4 typedef unsigned short uint16_t; 5 typedef short int16_t; 6 typedef unsigned int uint32_t; 7 typedef unsigned long long uint64_t; 8 typedef uint32_t data_type; 9 10 /******************************************************************************* 11 函数: data_type invert_num(data_type num) 12 描述:将一个数高低位翻转 13 输入参数: 14 num:要翻转数据位的数 15 返回值: 翻转高低位后的值 16 其他: 输入参数可以1、2、4、8字节类型数 17 *******************************************************************************/ 18 data_type invert_num(data_type num) 19 { 20 data_type temp = 0, sh = 0xf; 21 uint8_t i = 0; 22 for (i = 0; i < sizeof(data_type); i++) 23 { 24 temp |= (num & (sh << ((sizeof(data_type) - 1 - i) << 2))) << ((i << 3) + 4); 25 temp |= (num & (sh << ((sizeof(data_type) + i) << 2))) >> ((i << 3) + 4); 26 } 27 num = ((temp << 2) & 0xcccccccccccccccc) | ((temp >> 2) & 0x3333333333333333); 28 num = ((num << 1) & 0xaaaaaaaaaaaaaaaa) | ((num >> 1) & 0x5555555555555555); 29 30 return num; 31 } 32 33 int main() 34 { 35 uint32_t num = 0x12345678; 36 37 printf("Before inversion num = 0x%x\n", num); 38 num = invert_num(num); 39 printf("After inversion num = 0x%x\n", num); 40 41 return 0; 42 }
结果:
1 Before inversion num = 0x12345678 2 After inversion num = 0x1e6a2c48 3 请按任意键继续. . .