深入理解计算机系统_C语言中的位运算

简介

C语言中的位运算,即将数值按位做或、与、取反、异或、同或等运算。

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#include "stdafx.h"
void show_byte(unsigned char* start,int len)
{
int i;
for (i=0;i<len;i++)
{
printf("%.2x",start[i]);
}
printf("\n");
}


int _tmain(int argc, _TCHAR* argv[])
{
int data1 ,data2 ;
scanf("%d",&data1);
scanf("%d",&data2);
short m_Result;
printf("%d按位存储为:",data1);
show_byte((unsigned char*)&data1,sizeof(int));
printf("%d按位存储为:",data2);
show_byte((unsigned char*)&data2,sizeof(int));
m_Result = data1&data2;
printf("按位与运算:%d & %d = %d ,按位存储为:",data1,data2,m_Result);
show_byte((unsigned char*)&m_Result,sizeof(int));

m_Result = data1|data2;
printf("按位或运算%d | %d = %d,按位存储为:",data1,data2,m_Result);
show_byte((unsigned char*)&m_Result,sizeof(int));

m_Result = ~data1;
printf("按位取反运算~ %d = %d,按位存储为:",data1,m_Result);
show_byte((unsigned char*)&m_Result,sizeof(int));

m_Result = data1^data2;
printf("按位异或运算%d ^ %d = %d,按位存储为:",data1,data2,m_Result);
show_byte((unsigned char*)&m_Result,sizeof(int));
return 0;
}

结果