无符号长整型转字符串转换

4

我尝试像这样将无符号长整型转换为字符串

unsigned long long Data = 12;
char Str[20];

sprintf(Str, "%lld",Data);

当我想要查看时,但我总是看到00。

注:此内容未涉及IT技术相关内容。
Str[0],Str[1]....;

whats the wrong !!!


你确定 "%lld" 是有效的吗?我在文档中只看到了 "%ld"。 - leppie
1
就我所看到的,这是有效的代码(只需使用u而不是d)。告诉我们更多关于你正在做什么以及出了什么问题的指示。 - Jens Gustedt
如果这是针对PIC的话,那么对于无符号长整型的sprintf支持最好只能说是不稳定的,问题出在库文件中。 - Graham
3个回答

4
在大多数情况下,%llu 应该可以解决问题。但在某些 Windows 平台上,可能需要使用 %I64u

1
OP 可能没有使用 Windows 平台... 使用 USART_transmit('x'); 可能是 PIC 或 Atmega 平台。 - Prof. Falken

3

%lld 用于有符号的 long long,请使用 %llu 替代。


1

%llu应该能够正常工作,因为它已经被添加到标准中。但是,您可以使用一个安全版本的snprintf或者考虑编写比snprintf更好的自定义函数。以下是您可能会感兴趣的一个示例。

char *ulltostr(uint64 value, char *ptr, int base)
{
  uint64 t = 0, res = 0;
  uint64 tmp = value;
  int count = 0;

  if (NULL == ptr)
  {
    return NULL;
  }

  if (tmp == 0)
  {
    count++;
  }

  while(tmp > 0)
  {
    tmp = tmp/base;
    count++;
  }

  ptr += count;

  *ptr = '\0';

  do
  {
    res = value - base * (t = value / base);
    if (res < 10)
    {
      * --ptr = '0' + res;
    }
    else if ((res >= 10) && (res < 16))
    {
        * -- ptr = 'A' - 10 + res;
    }
  } while ((value = t) != 0);

  return(ptr);
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接