C++整数转换为任意进制字符串函数的一个理解问题

来源:百度知道 编辑:UC知道 时间:2024/05/26 13:17:57
我看到别人编写的一个程序,可以把一个整数转换为任意进制以字符串保存的数字,比如输入255,16,输出就为FF.
函数原型char *int2str(int num,int radix,char *result).
我现在大部分都理解了,惟独有一个地方不明白就是字符连接的问题.比如我输入35,16,将35转换为16进制,应该是23.在函数中,分别求出了对应的'2','3' 那么它是如何把'2'和'3'连接起来组成"23"这个字符串的呢?
函数源代码如下

#include <math.h>

char *int2str(int num,int radix,char *result) {
if (num<0) {
num=abs(num);
int2str(num,radix,result);
return result;
}
if (num%radix==0 && num/radix==0) return result;
result=int2str(num/radix,radix,result);
if (num%radix>10) *result='A'+num%radix-10;
else *result='0'+num%radix;
*(result+1)=NULL;
return result+1;
}
void main() {
int num,radix;
char string[1024];
cout<<"Enter an integer and the radix:";
cin>>num>>radix;
int2str(num,radix,string);
if (num<0) co

#include <iostream>
#include <stack>

using std::cout;
using std::cin;
using std::endl;

static char basestr[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
// this base code you can set yourself including the scale
char * bc(int inputnumber,int base,char *dsr);

int main()
{

char buf[1024];
for ( int j = 2; j < 3; ++j )
for ( int i = 0; i < 100; ++i )
cout << bc(i,j,buf) << endl ;
// i is the number ,j is the base
return 0;
}

char * bc(int inputnumber,int base,char * dsr)
{
if ( base >= strlen(basestr) || base < 2)
{
cout << "the base is bigger than the max basestr\n" ;
return NULL;
}

char *temp = dsr;
if ( inputnumber < base )
{
sprintf(dsr,"%d",inputnumber);
return temp;
}
std: