Stack order to achieve any hex conversion

Ideas analysis

We are all familiar with any conversion between binary and decimal, binary thinking is that any conversion to decimal bridge, turn first to decimal numbers, decimal and then turn into the target band.
Turn any binary decimal, for example: 45 (8), to decimal, which 4x8 = Result . 1 + 5x8 0 = = 32. 5 + 37 [; we can be achieved by cyclic loading.
Decimal turn any band, such as 55, turn into octal, need to use short division, as shown
Here Insert Picture Descriptionremainder of the first addition to the contrary on the low, after this advanced out of the relationship and the stack is very similar, we can use the stack to achieve.

The main code

int HexAnyToTen(char * num,int hex_begin){
	int i = 0,j = 0,k = 1;
	int counter = 0;
	int prior = 0;
	int length = strlen(num);
	printf("%d",length);
	for(i=0;i < length; i++)
	{
		k = 1;
		for(j=0;j<length-1-i;j++)
		{
			k *= hex_begin;
		}
		if(num[i] >= 48&&num[i] <= 57)
		{
			counter += (num[i] - '0')*k;
			prior = num[i] - '0';
		}
		else if(num[i] >= 65&&num[i] <= 90){
			counter += (num[i] - 55)*k;
			prior = num[i] - 55;
		}
		else if(num[i] >= 97&&num[i] <= 122){
			counter += (num[i] - 87)*k;
			prior = num[i] - 87;
		}
		else{
			if(i==0){
				continue;
			}
			else{
				counter = counter - prior*k*(hex_begin -1);
			}
		}
	}
	printf("%d\n",counter);
	return counter;
}

// 十进制转任意进制
void    HexToTenToAny(int num_hex_ten,int hex_after)
{
	SeqStack * s;
	int x;
	s = initSeqStack();
	while( num_hex_ten )
	{
		push(s, num_hex_ten % hex_after);
		num_hex_ten /= hex_after;
	}

	printf("转换成目的进制后:");

	while(!isEmpty(s))
	{
		x = getTop(s);
		pop(s);
		if(x > 9){
			printf("%c",x+87);
		}
		else{
			printf("%d",x);
		}
	}

	printf("\n");
}

Sample input

87475    // 待转换的数字
16			//待转换数字的进制
8				//目的进制

Sample output

转换成目的进制后:554101

All codes

Month-long small water Github

It also involves some unusual logic processing, do not know where to ask questions welcome.

Published 84 original articles · won praise 250 · Views 150,000 +

Guess you like

Origin blog.csdn.net/ygdxt/article/details/88601861