1. 程式人生 > >位運算之十進位制轉二進位制 十六進位制轉二進位制

位運算之十進位制轉二進位制 十六進位制轉二進位制

利用位運算進行進位制間的轉換
#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;
}