How to convert int to string with Pebble SDK in C

Just got my pebble and I'm playing with the SDK. I am new to C, but I know Objective-C. So, is there a way to create a formatted string like this?

int i = 1; NSString *string = [NSString stringWithFormat:@"%i", i]; 

And I can not use sprintf because there is NO malloc .

Basically I want to show int with text_layer_set_text(&countLayer, i);

+8
c string int pebble-watch pebble-sdk
source share
2 answers

Use snprintf() to populate the string buffer with the value of an integer variable.

 /* the integer to convert to string */ static int i = 42; /* The string/char-buffer to hold the string representation of int. * Assuming a 4byte int, this needs to be a maximum of upto 12bytes. * to hold the number, optional negative sign and the NUL-terminator. */ static char buf[] = "00000000000"; /* <-- implicit NUL-terminator at the end here */ snprintf(buf, sizeof(buf), "%d", i); /* buf now contains the string representation of int i * ie {'4', '2', 'NUL', ... } */ text_layer_set_text(&countLayer, buf); 
+14
source share

My favorite integer 2 for string functions is as follows. The first converts the base number 10 to a string, the second works for any base (for example, binary (base 2), hexadecimal (16), October (8) or decimal (10)):

 /* simple base 10 only itoa */ char * itoa10 (int value, char *result) { char const digit[] = "0123456789"; char *p = result; if (value < 0) { *p++ = '-'; value *= -1; } /* move number of required chars and null terminate */ int shift = value; do { ++p; shift /= 10; } while (shift); *p = '\0'; /* populate result in reverse order */ do { *--p = digit [value % 10]; value /= 10; } while (value); return result; } 

any base number: (taken from http://www.strudel.org.uk/itoa/ )

 /* preferred itoa - good for any base */ char * itoa (int value, char *result, int base) { // check that the base if valid if (base < 2 || base > 36) { *result = '\0'; return result; } char* ptr = result, *ptr1 = result, tmp_char; int tmp_value; do { tmp_value = value; value /= base; *ptr++ = "zyxwvutsrqponmlkjihgfedcba9876543210123456789abcdefghijklmnopqrstuvwxyz" [35 + (tmp_value - value * base)]; } while ( value ); // Apply negative sign if (tmp_value < 0) *ptr++ = '-'; *ptr-- = '\0'; while (ptr1 < ptr) { tmp_char = *ptr; *ptr--= *ptr1; *ptr1++ = tmp_char; } return result; } 

Since this is done with pointers and without depending on any C function that requires malloc, I see that it will not work in Pebble. However, I am not familiar with Pebble.

+2
source share

All Articles