All pastes #515521 Raw Edit

Anonymous

public text v1 · immutable
#515521 ·published 2007-05-28 07:22 UTC
rendered paste body
// sprintf that actually works
// By Sacky

stock sprintf(const format[],{Float,_}:...)
{
	new retstr[256],currarg = 1;
	for(new i=0,j=strlen(format);i<j;i++)
	{
		new forstr[8],len,tmpstr[32],bool:able = false;
		for(new a=i;a<j && a<sizeof(forstr);a++)
		{
			len = strlen(forstr);
			switch(format[i])
			{
				case '%':
				{
					if(!len) forstr[len] = format[i];
					else break;
				}
				case 'b','B','c','C','s','S':
				{
					if(len && forstr[len-1] == '%') forstr[len] = format[i];
					else break;
				}
				case 'd','D','f','F','i','I','x','X','0'..'9':
				{
					if(len && (forstr[len-1] == '%' || (forstr[len-1] >= '0' && forstr[len-1] <= '9'))) forstr[len] = format[i];
					else break;
				}
			}
		}
		len = strlen(forstr);
		if(forstr[0] == '%')
		{
			new num[6];
			for(new a=1;a<len-2;a++)
			{
				if(forstr[a] >= '0' && forstr[a] <= '9') num[a-1] = forstr[a];
				else break;
			}
			len = strlen(num);
			switch(forstr[len+1])
			{
				case 'b','B':
				{
					if(!len) continue;
					new val = getarg(currarg);
					for(new a=0,l=1;a<32;a++,l*=2) tmpstr[a] = (val & l) ? '1' : '0';
					able = true;
				}
				case 'c','C':
				{
					if(!len) continue;
					tmpstr[0] = getarg(currarg);
					tmpstr[1] = '\0';
					able = true;
				}
				case 'd','D','i','I':
				{
					new tmpforstr[8];
					if(len) format(tmpforstr,sizeof(tmpforstr),"%%dd",strval(num));
					else format(tmpforstr,sizeof(tmpforstr),"%d");
					format(tmpstr,sizeof(tmpstr),tmpforstr,getarg(currarg));
					able = true;
				}
				case 'f','F':
				{
					new tmpforstr[8];
					if(len) format(tmpforstr,sizeof(tmpforstr),"%%df",strval(num));
					else format(tmpforstr,sizeof(tmpforstr),"%f");
					format(tmpstr,sizeof(tmpstr),tmpforstr,Float:getarg(currarg));
					able = true;
				}
				case 's','S':
				{
					if(!len) continue;
					new a;
					while(getarg(currarg,a) != '\0')
					{
						tmpstr[a] = getarg(currarg,a);
						a++;
					}
					able = true;
				}
				case 'x','X':
				{
					new nib,val = getarg(currarg);
					for(new a=24,b=0;a>=0;a-=4,b++)
					{
						nib = (val >> i) & 0x0F;
						tmpstr[b] = (nib < 10) ? (nib + 0x30) : (nib + 0x37);
					}
					new a=strval(num),b=strlen(tmpstr);
					if(a > b)
					{
						new ctmpstr[sizeof(tmpstr)],c;
						while(c < sizeof(tmpstr))
						{
							ctmpstr[c] = tmpstr[c];
							c++;
						}
						for(new d=0;d<sizeof(tmpstr);d++)
						{
							if(d < a-b) tmpstr[d] = '0';
							else tmpstr[d] = ctmpstr[d-(a-b)];
						}
					}
					able = true;
				}
			}
		}
		if(able)
		{
			strcat(retstr,tmpstr);
			i+=strlen(forstr)-1;
			currarg++;
		}
		else format(retstr,sizeof(retstr),"%s%c",retstr,format[i]);
	}
	return retstr;
}