编程完成如下接口,以实现32位整数的16进制和10进制转换
函数原型:int convert(const cahr* str,char * convertedStr)
要求:str为输入字符串,convertedStr为输出字符串,即为转换之后的字符串,函数返回值用以判断转换是否成功,成功返回0,;当输入字符串str为16进制形式,如0x12时,输出10进制形式,如18,当输入字符串为10进制形式,如18时,输出16进制形式0x12,;除了printf,不得使用任何的库函数;
/*十进制和任意进制转换*/ #include<iostream> #include<string> #include<algorithm> using namespace std; int main() { int m,n;//m代表十进制 n代表任何进制 while(cin>>m>>n) { string res; bool flag=flase; if(m<=0) { flag=true; m=abs(m); } while(m) { int temp=m%n; if(temp>=10) { temp+=55; char temp1=char (temp); res+=temp1; } else res+=temp+'0'; m/=n; } if(flag) res+='-'; reverse(res.begin(),res.end()); cout<<res<<endl; } return 0; }
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
using namespace std;
int convert(const char* str,char* convertedStr){
long long value = 0;
int len = strlen(str);
char temp[100];
if(str[0]=='0' && str[1]=='x'){//十六进制转十进制
for(int i=2;i<len;i++){
if(str[i]=='A')
value = value*16 + 10;
else if(str[i]=='B')
value = value*16 + 11;
else if(str[i]=='C')
value = value*16 + 12;
else if(str[i]=='D')
value = value*16 + 13;
else if(str[i]=='E')
value = value*16 + 14;
else if(str[i]=='F')
value = value*16 + 15;
else
value = value*16 + (str[i]-'0');
}
if(value==0){//处理等于0
convertedStr[0] = '0';
convertedStr[1] = '\0';
}
else{
int j=0;
while(value>0){
temp[j++] = '0' + value%10;
value /= 10;
}
temp[j] = '\0';
j=0;
for(int i=strlen(temp)-1;i>=0;i--){
convertedStr[j++] = temp[i];
}
convertedStr[j] = '\0';
}
}
else{//十进制转十六进制
for(int i=0;i<len;i++){
value = value*10 + (str[i]-'0');
}
convertedStr[0] = '0';
convertedStr[1] = 'x';
if(value==0){
convertedStr[2] = '0';
convertedStr[3] = '\0';
}
else{
int j=0;
while(value>0){
if(value%16==10)
temp[j++] = 'A';
else if(value%16==11)
temp[j++] = 'B';
else if(value%16==12)
temp[j++] = 'C';
else if(value%16==13)
temp[j++] = 'D';
else if(value%16==14)
temp[j++] = 'E';
else if(value%16==15)
temp[j++] = 'F';
else
temp[j++] = '0' + value%16;
value /= 16;
}
temp[j] = '\0';
j=2;
for(int i=strlen(temp)-1;i>=0;i--){
convertedStr[j++] = temp[i];
}
convertedStr[j] = '\0';
}
}
return 0;
}
int main()
{
char *str = (char*)malloc(100);
char *convertedStr = (char*)malloc(100);
scanf("%s",str);
convert(str,convertedStr);
printf("%s",convertedStr);
return 0;
}