如何将unsigned long转换为string

时间:2010-04-25 19:56:42

标签: c

在C语言中,如何将 unsigned long 值转换为字符串( char * )并保持我的源代码可移植,或者只是重新编译它以在其他字符串上工作平台(没有重写代码?

例如,如果我有sprintf(buffer, format, value),如何使用与平台无关的方式确定缓冲区的大小?

6 个答案:

答案 0 :(得分:25)

const int n = snprintf(NULL, 0, "%lu", ulong_value);
assert(n > 0);
char buf[n+1];
int c = snprintf(buf, n+1, "%lu", ulong_value);
assert(buf[n] == '\0');
assert(c == n);

答案 1 :(得分:6)

标准方法是使用sprintf(buffer, "%lu", value);value的字符串代表写入buffer。但是,溢出是一个潜在的问题,因为sprintf会很快(并且在不知不觉中)写入缓冲区的末尾。

这实际上是sprintf的一大弱点,通过使用流而不是缓冲区在C ++中部分修复。通常的“答案”是分配一个非常大的缓冲区,不太可能溢出,让sprintf输出到那个,然后使用strlen来确定生成的实际字符串长度,calloc缓冲区(那个大小+ 1)并将字符串复制到那个。

This site在一定程度上讨论了这个问题和相关问题。

某些库提供snprintf作为替代方案,允许您指定最大缓冲区大小。

答案 2 :(得分:5)

你可以编写一个从unsigned long转换为str的函数,类似于ltostr库函数。

char *ultostr(unsigned long value, char *ptr, int base)
{
  unsigned long t = 0, res = 0;
  unsigned long 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);
}

您可以参考我的博客here,其中通过示例解释了实施和使用情况。

答案 3 :(得分:2)

char buffer [50];

unsigned long a = 5;

int n=sprintf (buffer, "%lu", a);

答案 4 :(得分:2)

尝试使用sprintf

unsigned long x=1000000;
char buffer[21];
sprintf(buffer,"%lu", x);

编辑:

请注意,您必须提前分配缓冲区,并且不知道数字实际存在多长时间。我假设32位long s,可以产生大到10位的数字。

请参阅Carl Smotricz的答案,以便更好地解释所涉及的问题。

答案 5 :(得分:0)

对于long值,您需要为无符号十进制整数添加长度信息'l'和'u',

作为可用选项的参考,请参阅sprintf

#include <stdio.h>

    int main ()
    {
      unsigned long lval = 123;
      char buffer [50];
      sprintf (buffer, "%lu" , lval );
     }
相关问题