C++将int型数据二进制输出

版权声明:作者:weizu_cool https://blog.csdn.net/qq_26460841/article/details/87977235

首先是大端、小端的判断:

void JudgeSystem()
{
	int a = 0b00000001;
	char * p = (char *)&a;
 
	if (0b00000001 == *p)
	{
		cout<<"小端"<<endl; 
	}
	else
	{
		cout<<"大端"<<endl; 
	}
}

解决方式1:除二取余

void showbit2(int a){
	/*
	除二取余: 
		6/2=3 % 0
		3/2=1 % 1
		1/2=0 % 1
		=> 110
	*/
	int ret = 0;
	while(a){
		ret = ret*10 + (a % 2); 
		a = a / 2;
	} 
	cout<<ret<<endl;
}

 方法二:利用数据的存放特点。位置取元素判断 int 4个字节,char 1个字节, 1个字节8位 

int为4字节,char为1字节,定义char类型的指针*p,在p++四次后,可以将int的32字节的内存空间遍历完毕。

也就是最多遍历四次p,在每次遍历的时候,我们需要判断数据位是0还是1,此时用到的是左移一位,由于左移动低位补0,所以在做移动的过程中始终满足一个字节,我们可以判断高位。

//按位置取元素判断 int 4个字节,char 1个字节, 1个字节8位 
void showbit(int a){
	char *p = (char *)&a;
	char byte;
	int len = 0;
	if(a<=255) len = 1;
	else if (a>255 and a<=65535) len = 2;
	else if (a>65535 and a<16777215) len = 3;
	else len = 4;
	for( int i=0;i<len;i++){//字节 
		byte = *p;
		for(int j=0;j<8;j++){//取位 
			if(0b10000000 & byte) cout<<"1";  //如果直接输出byte,输出的是整个char8字节,那么有可能就是特殊符号 
			else cout<<"0";
			byte = byte << 1;
		}
		cout<<" ";
		p++;
	}
}

其余的测试main:

#include<iostream>
using namespace std;

int main(){
	int a = 0b00000001000000100000001100000100;
	cout<<a<<endl; 
	JudgeSystem();
	showbit2(5);
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_26460841/article/details/87977235