8

刚拿到我的 Pebble,我正在玩 SDK。我是 C 新手,但我知道 Objective-C。那么有没有办法创建这样的格式化字符串?

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

而且我不能使用sprintf,因为没有malloc

我基本上想显示int一个text_layer_set_text(&countLayer, i);

4

2 回答 2

14

用于snprintf()用整数变量的值填充字符串缓冲区。

/* 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
 * i.e. {'4', '2', 'NUL', ... }
 */
text_layer_set_text(&countLayer, buf);
于 2014-04-03T16:08:01.713 回答
2

我最喜欢的 2 个通用整数到字符串函数如下。第一个将基数为 10 的整数转换为字符串,第二个适用于任何基数(例如二进制(基数 2)、十六进制(16)、八进制(8)或十进制(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;
}

任何基数:(取自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;
}

由于它是用指针​​完成的,并且不依赖于任何需要 malloc 的 C 函数,所以我明白它在 Pebble 中不起作用的原因。但是我不熟悉Pebble。

于 2014-06-09T20:15:58.153 回答