C/C++ >> Convert an unsigned long integer to a character string in Linux?
Posted by Huxly on 20:08:00 08-11-2001
I can't find a C function like the DOS
ultoa that will convert an unsigned
long integer into a character string,
in Linux.
Does Linux have a C function like ultoa
by a different name?
How do you convert an unsigned long
integer into a character string in
Linux using C ?
Posted by SilentStrike on 21:19:00 08-11-2001
#include <stdio.h>

int main(int argc, char *argv[])
{
char string[10];
unsigned long num=1234;
sprintf(string, "%d",num);
printf(string);
return 0;
}

[ This Message was edited by: SilentStrike on 2001-08-11 21:20 ]
Posted by Peter on 22:34:00 08-11-2001
Haha... that's it, do your own function .

Neat.
Posted by SilentStrike on 08:15:00 08-12-2001
k .


#include <stdio.h>

char longToChar(unsigned long num) {
return (char) (num + '0');
}

void longToString(unsigned long num, char* dest) {
/* test exceptional case of num == 0 */
if (num == 0) {
*dest='0';
dest++;
*dest='\0';
return;
}

unsigned long copy=num;
unsigned long currentDivisor=1;

while (copy --> 0) {
copy /= 10;
currentDivisor *=10;
}

currentDivisor/=10;

while (currentDivisor --> 0) {
*dest = longToChar( (num / currentDivisor) % 10);
dest++;
currentDivisor/=10;
}

*dest = '\0';
}



int main(int argc, char *argv[])
{
char string[10];

for (unsigned long count=0; count



[ This Message was edited by: SilentStrike on 2001-08-12 08:18 ]
Posted by robost86 on 11:23:00 08-12-2001
The correct format for signed longs is %l, and for unsigned longs %lu. And I think you shouldn't write functions like this in C, use the library functions, they are optimized for your system and alot faster
Posted by SilentStrike on 20:17:00 08-12-2001
For the most part I agree... except you can make your own functions more flexible (like write the number in an arbitrary base), and it's fun to take on the challenge of rewriting the libs sometimes.


#include <stdio.h>

unsigned long base=10;

char longToChar(unsigned long num) {
if (num 0) {
copy /= base;
currentDivisor *=base;
}

currentDivisor/=base;

while (currentDivisor --> 0) {
*dest = longToChar( (num / currentDivisor) % base);
dest++;
currentDivisor/=base;
}

*dest = '\0';
}

void test(int min, int max) {
char string[15];
for (unsigned long count=min; count
Posted by robost86 on 21:05:00 08-12-2001
Yeah, you can get what you want and skip the crap if you do it yourself

I like reinventing wheels, but I know it's not always good.
Posted by KaGez on 15:58:00 08-24-2001
hmm ... but you have to watch it ... I think a unsigned long is bigger than a char ... or isn't it ? if it is , it'll cause major mem errors and if you're lucky the program will crash , if you're unluck your OS will screw up in a few mins ..
[addsig]