gbadev.org forum archive

This is a read-only mirror of the content originally found on forum.gbadev.org (now offline), salvaged from Wayback machine copies. A new forum can be found here.

Beginners > split an integer

#106196 - QuantumDoja - Mon Oct 16, 2006 6:13 pm

Hi, I have an int: 123 and i want to split it into a char array...how would i do this in c?

i need: char output[] = {'1','2','3'};

any help appreciated.

Thanks
_________________
Chris Davis

#106204 - Edelnutte - Mon Oct 16, 2006 7:49 pm

Dunno if it works but try something like itoa from stdlib.h

#106211 - kusma - Mon Oct 16, 2006 8:32 pm

char temp[256];
sprintf(temp, "%d", my_int);

that should give you what you wanted, a char-array filled with each digits ascii-code.

#106214 - sgeos - Mon Oct 16, 2006 8:47 pm

If you want to force it to have 3 digits, use
Code:
#define BUFFER_MAX 20
char buffer[BUFFER_MAX];
int value = 2;
sprint(buffer, "%03d", value);
This will give you "002".

-Brendan

#106262 - QuantumDoja - Tue Oct 17, 2006 10:30 am

Thanks, works fine now :-)
_________________
Chris Davis

#106318 - poslundc - Tue Oct 17, 2006 9:06 pm

If performance with sprintf becomes problematic for you, you can also consider posprintf.

Dan.