Q5.6

#include <iostream>
using namespace std;

void print_binary(int x){
    string s = "";
    for(int i=0; i<32 && x!=0; ++i, x >>= 1){
        if(x&1) s = "1" + s;
        else s = "0" + s;
    }
    cout<<s<<endl;
}

int bit_swap(int a)
{
	return (a & 0x55555555) << 1 | (a & 0xaaaaaaaa) >> 1; 	
}

int main(void)
{
	int a = -2;
	cout << "a:" << a << endl; print_binary(a);
	cout << "after bit_swap: " << bit_swap(a) << endl;
	print_binary(bit_swap(a));
	
	cout << "*************************************************" << endl << endl;
	
//	int test = -2;
//	print_binary(test);
//	cout << test << endl << endl;
	
	cout << "间接输出: " << endl;
	cout << "1. c = -2 & 0xaaaaaaaa" << endl;
	int c = -2 & 0xaaaaaaaa;	
	print_binary(c);
	//cout << c << endl << endl;
	
	cout << "2. d = c >> 1" << endl;
	int d = c >> 1;
	print_binary(c >> 1);     cout << endl;            //有符号数右移,高位补1 
	//cout << d << endl;
	
	//cout << bit_swap(a) << endl;
	cout << "直接输出:(-2 & 0xaaaaaaaa) >> 1" << endl;  //仅有31位,说明最高位为0,验证了Hawstain的说法:(x & 0xAAAAAAAA) 得出的结果是无符号数
														 //无符号数右移,最高位补0 
	print_binary((-2 & 0xaaaaaaaa) >> 1);
	
	return 0;
}


结果如下:



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值