码迷,mamicode.com
首页 > 编程语言 > 详细

C/C++01: 善用位计算

时间:2015-09-27 22:40:28      阅读:238      评论:0      收藏:0      [点我收藏+]

标签:

原文地址: http://blog.csdn.net/morewindows/article/details/7354571

推荐书籍: Hacker‘s Delight

1.判断奇偶

1 if (a & 1)
2 {
3     printf("%i is an odd number", a);
4 }

2.交换两数

1 void Swap(int &a, int &b)
2 {
3     if (a != b)
4     {
5         a ^= b;
6         b ^= a;
7         a ^= b;
8     }
9 }

3.变换符号

1 int SignReversal(int a)
2 {
3     return ~a + 1;
4 }

4.求绝对值

1 int my_abs(int a)
2 {
3     int i = a >> 31;
4     return ((a ^ i) - i);
5 }

注:如果a是负数,那么a右移31位为-1

5.高低位交换

 1 #include <stdio.h>
 2 
 3 template <class T>
 4 void PrintfBinary(T a)
 5 {
 6     int i;
 7     for (i = sizeof(a) * 8 - 1; i >= 0; --i)
 8     {
 9         if ((a >> i) & 1)
10             putchar(1);
11         else
12             putchar(0);
13         if (i == 8)
14             putchar( );
15     }
16     putchar (\n);
17 }
18 
19 int main()
20 {
21     printf("Before: ");
22     unsighed short a = 12345;
23     PrintfBinary(a);
24 
25     printf("After: ");
26     a = (a >> 8) | (a <<8);
27     PrintfBinary(a);
28     return 0;
29 }

6.二进制逆序

 1 #include <stdio.h>
 2 int main()
 3 {
 4     printf("Before: ");
 5     unsigned short a = 12345;
 6     PrintfBinary(a);
 7 
 8     printf("After: ");
 9     a = ((a & 0xAAAA) >> 1) | ((a & 0x5555) << 1);
10     a = ((a & 0xCCCC) >> 2) | ((a & 0x3333) << 2);
11     a = ((a & 0xF0F0) >> 4) | ((a & 0x0F0F) <<4);
12     a = ((a & 0xFF00) >> 8) | ((a & 0x00FF) <<8);
13     PrintfBinary(a);
14 
15     return 0;
16 }

7.二进制中1的个数

 1 #include <stdio.h>
 2 int main()
 3 {
 4     unsigned short a = 12345;
 5     a = ((a & 0xAAAA) >> 1) + (a & 0x5555);
 6     a = ((a & 0xCCCC) >> 2) + (a & 0x3333);
 7     a = ((a & 0xF0F0) >> 4) + (a & 0x0F0F);
 8     a = ((a & 0xFF00) >> 8) + (a & 0x00FF);
 9     printf("Have %i ones in binary", a);
10     return 0;
11 }

C/C++01: 善用位计算

标签:

原文地址:http://www.cnblogs.com/toorist/p/4842373.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!