位运算

输入一个十进制整数,数据范围要求在0~65535(无符号短整型),要求将这个整数的二进制数的最后一位变成0(如果这个整数的最后一位已经是0,就不用变了)。

 1 #include<iostream>

 2 #include<iomanip>

 3 using namespace std;

 4 void f(unsigned short int m)

 5 {

 6     int i;

 7     int g[100]={0};

 8     int t=0;

 9     while(m!=0)

10     {

11         int x=m%2;

12         g[t++]=x;

13         m=m/2;

14     }

15     for(i=1;i<=16-t;i++)

16     cout<<0;

17     for(i=t-1;i>=0;i--)

18     cout<<g[i];

19     cout<<endl;

20 }

21 int main()

22 {

23     unsigned short int b,c;

24     cout<<"请输入b的值(c的初始值是1):";

25     cin>>b;

26     unsigned short int t=b;

27     c=1;

28     cout<<endl;

29     cout<<"b所占的字节数是:"<<sizeof(b)<<endl;

30     cout<<"c所占的字节数是:"<<sizeof(c)<<endl;

31     cout<<endl;

32     cout<<"b的初始二进制数:";

33     f(b);

34     cout<<"c的初始二进制数:";

35     f(c);

36     cout<<endl;

37     c=~c;

38     cout<<"c按位求反(c=~c)后的十进制数是:";

39     cout<<c<<endl;

40     cout<<"b此时的十进制数是:";

41     cout<<b<<endl;

42     cout<<endl;

43     cout<<"c按位求反后的二进制数:";

44     f(c);

45     cout<<endl<<"经过运算:c=c&b 以后:"<<endl;

46     cout<<endl;

47     cout<<"运算后的b二进制数";

48     b=c&b;

49     f(b);

50     cout<<endl;

51     cout<<"最终结果是:";

52     cout<<endl<<endl;

53     cout<<"c的十进制数是:"<<c<<endl;

54     cout<<"b的十进制数是:"<<b<<endl;

55     cout<<endl;

56     cout<<"运算前的b的十进制数是:"<<t<<endl;

57     cout<<"运算后的b的十进制数是:"<<b<<endl;

58     cout<<"运算前的b的二进制数是:";

59     f(t);

60     cout<<"运算后的b的二进制数是:";

61     f(b);

62     return 0;

63 }
View Code

 

你可能感兴趣的:(位运算)