位运算之十进制转二进制 十六进制转二进制

时间:2021-03-10 03:38:14
利用位运算进行进制间的转换
#include <stdio.h>
#include <string.h>

int inttoBin(unsigned int num)
{
	int i;
	unsigned int mask = 0x80000000;
	for(i = 0; i < 32; i++)
	{
		if((num & mask) == mask)
		{
			printf("1");
		}
		
		else
		{
			printf("0");
		}

		num = num << 1;
		
		if((i + 1) % 4 ==0)
		{
			printf(" ");
		}
	}
	
	printf("\n");
}

int inttoox(unsigned int num)
{
	int i;
	unsigned int temp = num;

	char s[11];
	memset(s,0,sizeof(char));
	
	s[0] = "0";
	s[1] = "x";
	s[10] = "\0";

	unsigned int mask = 0x0000000f;

	for(i = 2; i < 10; i++)
	{
		if((temp & mask) > 10)
		{
			s[11-i] = (temp & mask) - 10 + 'a'; 
		}
		else
		{
			s[11-i] = (temp & mask) + '0';
		}
		
		temp = temp << 4;
	}
	
    printf("result = %s\n",s);
	//printf("result = %s\n",s);
}

int main()
{
	unsigned int num;
	char s[11];
	
	printf("intput a number\n");
	scanf("%u",&num);
	
	inttoBin(num);
	inttoox(num);

	return 0;
}