我想制作一个自定义ITOA函数,将大数字放入小字符串中,这就是我编码的内容:
main(){
printf("itoa(2000000000,36)= '%s'",itoa(2000000000,36));
printf("itoa(36,36)= '%s'",itoa(36,36));
printf("itoa(37,36)= '%s'",itoa(37,36));
return 1;
}
stock itoa(val, base)
{
new buf[1024] = {0,...};
new i = 1023;
new LETTERZ[37] = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z',0};
for(; val && i; --i, val /= base)
buf[i] = LETTERZ[val % base];
return buf[i+1];
}
它基于此页面中的“C”代码:http://www.jb.man.ac.uk/~slowe/cpp/itoa.html
但不知何故,这是输出:
[20:34:35] itoa(2000000000,36)='X' [20:34:35] itoa(36,36)='1' [20:34:35] itoa(37,36)='1'
这是完全错误的,我不知道期望哪个输出但是36和37肯定不能是相同的输出而2 000 000 000不能只是'X',因为X被接受是35岁,而不是2 000 000 000, 我认为ZZ应该是1295 ...我想把它建立在十六进制系统上,但是用所有的alfabet字母。
有人能告诉我这里有什么问题吗?
我正在使用一种名为PAWN(也称为SMALL)的无类型语言,后来我想在VB.NET中使用此代码
答案 0 :(得分:0)
/* itoa example */
#include <stdio.h>
#include <stdlib.h>
int main ()
{
int i;
char buffer [33];
printf ("Enter a number: ");
scanf ("%d",&i);
itoa (i,buffer,10);
printf ("decimal: %s\n",buffer);
itoa (i,buffer,16);
printf ("hexadecimal: %s\n",buffer);
itoa (i,buffer,2);
printf ("binary: %s\n",buffer);
return 0;
}
您只提供数字和基数,但参数2需要指向已分配的char的指针。使用缓冲区或尝试NULL,因此该函数将返回结果。
答案 1 :(得分:0)
这个解决方案似乎很简单,返回buf [i + 1]只返回一个字符所以我所做的是让它返回一个数组:
new _s@T[4096];
#define sprintf(%1) (format(_s@T, SPRINTF_MAX_STRING, %1), _s@T)
main(){
new num = atoi("ABCDEFG",36);
printf("%d",num);
printf("%s",itoa(num,36));
return 1;
}
stock itoa(val, base)
{
new buf[1024] = {0,...};
new LETTERZ[37] = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z',0};
for(new pos = 0; val;++pos,val = floatround(val/base,floatround_floor))
strins(buf,sprintf("%c",LETTERZ[val % base]),0);
return buf;
}
stock atoi(val[], base)
{
new CURRNUM = 0;
new len = strlen(val);
new LETTERZ[37] = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z',0};
for(new i = 0; i < len; ++i)
{
for(new x = 0; x < base; ++x)
{
new y = (len-i)-1;
if(val[y] == LETTERZ[x])
{
CURRNUM += x*floatround(floatpower(base,i));
}
}
}
return CURRNUM;
}