delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/1998/07/28/12:48:27

Date: Tue, 28 Jul 1998 11:48:58 -0500 (CDT)
From: Andrew Deren <aderen AT eecs DOT uic DOT edu>
To: Niki Ruusunko <ultrastar AT online DOT tietokone DOT fi>
cc: djgpp AT delorie DOT com
Subject: Re: sprintf and 64 bit integers
In-Reply-To: <msg316796.thr-3d13781.f625b@online.tietokone.fi>
Message-ID: <Pine.GSO.3.96.980728114625.5503A-100000@bert.eecs.uic.edu>
MIME-Version: 1.0

You can just use this little function I came up with now instead of
sprintf:
void LongLongToChar(char* string, long long number)
{
	long long div = number;
	long mod;
	int i = 0;
	int len;
	char tempChar;
	
	do {
		mod = div % 10;
		div = div / 10;
		string[i++] = mod + '0'; /* that is zero */	
	} while (div > 0);

	string[i] = '\0';
	len = i - 1;
	
	/* now just reverse the string */
	for (i=0; i<(len+1)/2; i++) {
		tempChar = string[i];
		string[i] = string[len-i];
		string[len-i] = tempChar;
	}
}

If you also need to support negative numbers, just first test whether the
number is negative it it is make it possitive and insert '-' at the
beginning of the string.

On Tue, 28 Jul 1998, Niki Ruusunko wrote:

> I have this problem with a function I use to do thousands separators to
> integers. Here is the code:
> 
> char * LargeInt(unsigned int bignumber)
>         {
>         int counter = -1, i, i2 = 0, sep = 0;
>         char string1[21];
>         char string2[27];
>         sprintf(string1, "%d", bignumber);
>         i = strlen(string1);
>         while(i >= 0)
>                 {
>                 if (counter < 3)
>                         {
>                         string2[i2] = string1[i];
>                         counter++;
>                         }
>                 else
>                         {
>                         string2[i2] = ',';
>                         i2++;
>                         string2[i2] = string1[i];
>                         counter = 1;
>                         sep++;
>                         }
>                 i--;
>                 i2++;
>                 }
>         i = 0;
>         i2 = strlen(string1) + sep;
>         while(i2 >= 0)
>                 {
>                 tmpInt[i] = string2[i2];
>                 i++;
>                 i2--;
>                 }
>         return tmpInt;
>         }
> 
> It isn't very good function but it works (on ints that is). The problem is
> that I need it to support the "long long" -variables I use. Sprintf doesn't
> compile with a long long as the argument (it says: "warning: int format,
> different type arg (arg 3)") so I'm asking if there is an alternate
> function to make a string out of an int (or, a long long in this case).
> 
> Of course, if you know how to make the separators some better way, please
> tell me.
> 

- Raw text -


  webmaster     delorie software   privacy  
  Copyright © 2019   by DJ Delorie     Updated Jul 2019