关于进制转换的一点思考

来源:互联网 发布:臭臭ddos软件 编辑:程序博客网 时间:2024/05/21 09:24
关于进制转换的一点思考
在计算机中对于数来说,本质都是一样的,二进制流,不涉及数制转换,但是有些场景下需要在终端上以字符的输入输出表示相应的进制转换,下面给出两种方法实现输入十进制到其他进制之间的转换方法。
1.c语言中进制转换库函数可以使用itoa:
char *_itoa(
   int value,
   char *str,
   int radix 
);
Parameters:
value:Number to be converted.
str:String result.
radix:Base of value,which must be in the range 2–36.
Return Value
Each of these functions returns a pointer to str. There is no error return.


example:
#include <stdio.h>
#include <stdlib.h>


int main(int argc, char* argv[])
{
long input;
int k;
char buffer[128];


printf("put the algorism number:");
scanf("%ld", &input);


printf("translate %d to...(2,8,16)?:", input);
scanf("%d", &k);


itoa(input,buffer,k);
printf("the digit transfered is:");
printf("%s\n",buffer);
return 0;
}


2.按照10进制转换多进制的定义,使用链表头插法显示
example:
#include <stdio.h>
#include <malloc.h>


typedef struct node_tag
{
char c;
struct node_tag *next;
}node,*p_node;


//初始化node
void init_node(p_node node)
{
node->c = 's';
node->next = NULL;


return;
}


int main(int argc, char* argv[])
{
node head;
node *tmp = NULL;
int k;
int t;
long input;
char c[] = "0123456789ABCDEF";

init_node(&head);


printf("put the algorism number:");
scanf("%ld", &input);


printf("translate %d to...(2,8,16)?:", input);
scanf("%d", &k);


while(input != 0) 
{
t = input % k;
input /= k;
//头插法
tmp = (p_node)malloc(sizeof(node));
tmp->c = c[t];
tmp->next = head.next;
head.next = tmp;
}
printf("the digit transfered is:");
while(head.next)
{
printf("%c",head.next->c);
tmp = head.next;
head.next = tmp->next;
free(tmp);
}


return 0;
}


对于多进制到十进制转换的其实时十进制到多进制转换的逆过程,以二进制到十进制转换为例。二进制转换十进制有个通用公式,(1或0)*2^0(次方)+ (1或0)*2^1(次方)+……(1或0)*2^N(次方)比如:二进制1010转换十进制  ==  (0*2^0)+(1*2^1)+(0*2^2)+(1*2^3) = 0+2+8+0 = 10。
程序中results += (temp[i] - '0') * pow(2,i);则是使用到上面相应的公式。temp[i]-‘0’需要特别注意,因为在C语言中没有将字符char类型转换为int类型的方法,相应的转换需要自行运算,而在该程序中temp[i]-‘0’则是将char转换为int的方法。


example:
#include <stdio.h>
#include <math.h>


int main(int argc,char* argv[])
{
long input;
int k;
char buffer[128];
int result = 0;
int i;
int len;
double tmp;


printf("put the number:");
scanf("%s", buffer);
len = strlen(buffer);


printf("translate %s to algorism:", buffer);
scanf("%d", &k);
printf("base %d the transfered is:",k);
for(i = len - 1;i>=0;i--)
{
result += (buffer[len-1-i] - '0') * pow(k,i);
}


printf("algorism:%d\n",result);

}
0 0
原创粉丝点击