You're here: Snippet Directory » C/C++ (495)
Language:

longtostr

Language: English
Programming Language: C
Published by: zaf [not registered]
Last Update: 5/15/2006
Views: 155


Description

The reverse of strtol. Converts a long (signed or unsigned) to a string. Also known as a more complex version of itoa. Can output in any base.

Code

1 /* Converts a long int to a string. Can be signed or unsigned. 2 * Set sign to be non-zero to treat 'in' as signed. Otherwise its 3 * treated as unsigned. Set base to be the base of the output (usually 4 * 10). Digits greater than 9 are represented by letters from 'a'. 5 * With Bases above 36, or below 1, results are undefined. 6 * 'out' must be long enough to take the largest number, plus a '-'. 7 * To pass an unsigned long, do a cast and set sign to 0, eg: 8 * longtostr((signed) number, outstr, 0, 10); 9 */ 10 void longtostr(signed long in, char *out, int sign, int base) 11 { 12 char *p=out,*r; 13 unsigned long u; 14 /* Deal with the sign */ 15 if (sign && in < 0) { 16 *p = '-'; p++; 17 u = (unsigned) in * -1; 18 } else 19 u = (unsigned) in; 20 /* Process the number, output to the string in reverse */ 21 r = p; 22 do { 23 /* Turn the digit into a character */ 24 *p = u%base > 9 ? 'a' + u%base - 10 : '0' + u%base; 25 u=u/base; 26 p++; 27 } while(u != 0); 28 29 *p=0; 30 p--; 31 /* Reverse The String. */ 32 while(r < p) { 33 *p ^= *r ^= *p ^= *r; /* A Crazy Swap */ 34 p--; r++; 35 } 36 }

No comments avaiable

Add a comment

Name *  

Email (won't be displayed) *    

Website  

Comment *  

Sicherheitscode Security Code *    

RSS