How can I use the itoa function?

Hi, I am very new to Spark. I am trying to get some code moved from Arduion over to Spark, and it uses the itoa() funciton. I can see the itoa function is implemented in the firmware source code, but I cannot figure out how to get access to it. Do I have to copy the source code in to my project? Can anyone give me a hand? Thanks!

I can’t try this right now as the only Core I have with me is Bricked… (making it work too hard!) but it compiles.

But give this a try and let me know if you have any questions :smile:

int number = 12345;
char string1[5] = "";

// allow us to use itoa() in this scope
extern char* itoa(int a, char* buffer, unsigned char radix);

// If the above does not work just redefine itoa here
/* 
char* itoa(int a, char* buffer, unsigned char radix){
	if(a<0){
		*buffer = '-';
		a = -a;
		ultoa(a, buffer + 1, radix);
	}else{
		ultoa(a, buffer, radix);
	}
	return buffer;
}
*/

void setup() {
    pinMode(D7, OUTPUT);
    digitalWrite(D7, HIGH);
    Serial.begin(9600);
    while (!Serial.available()); // After Core D7 LED turns on, open serial monitor and press enter!
    digitalWrite(D7, LOW);
}

void loop() {
    // ITOA
    itoa(number, string1, 10); // convert int number as base 10 to char string
    Serial.println(string1);   // print string1
    
    // STRING CLASS
    String string2(number,(uint8_t)10); // convert int number as base 10 char string via String object constructor
    Serial.println(string2);  // print string2
    
    // STRING CLASS
    string2 = "The number is: " + number; // convert int number as base 10 to char string via String concat
    Serial.println(string2);  // print string2
    
    number++;                 // increment number
    delay(500);               // chill for 500ms
}
2 Likes

Thanks Bdub. That did it. I regret I didn’t think of it myself. Still wrapping my head around the fact that while the web front end abstracts a lot of things, it’s all basically just plain-ol’ C running in the background…

2 Likes

Just tried this and it verifies fine. However, when I try to flash the code, I get the following error:

…/…/…/build/target/user/platform-8/libuser.a(teststring.o): In function loop': teststring.cpp:31: undefined reference toitoa(int, char*, unsigned char)'
collect2: error: ld returned 1 exit status

I got a int to char array conversion to work by using sprintf, but still would be nice to know why this compiles but doesn’t flash.

Try adding extern “C” before the declaration of the itoa function since it should be linked with C linkage, rather than C++. :smile:

Try this:

int i;
char buffer [33];
itoa (i,buffer,10);

Referenced from: Convert integer to string