Linux中的itoa函数在哪里?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/190229/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Where is the itoa function in Linux?
提问by Adam Pierce
itoa()is a really handy function to convert a number to a string. Linux does not seem to have itoa(), is there an equivalent function or do I have to use sprintf(str, "%d", num)?
itoa()是一个非常方便的将数字转换为字符串的函数。Linux 似乎没有itoa(),是否有等效的功能或我必须使用sprintf(str, "%d", num)?
采纳答案by Matt J
EDIT: Sorry, I should have remembered that this machine is decidedly non-standard, having plugged in various non-standard libcimplementations for academic purposes ;-)
编辑:抱歉,我应该记得这台机器绝对是非标准的,libc出于学术目的插入了各种非标准实现;-)
As itoa()is indeed non-standard, as mentioned by several helpful commenters, it is best to use sprintf(target_string,"%d",source_int)or (better yet, because it's safe from buffer overflows) snprintf(target_string, size_of_target_string_in_bytes, "%d", source_int). I know it's not quite as concise or cool as itoa(), but at least you can Write Once, Run Everywhere (tm) ;-)
正如itoa()几个有用的评论者所提到的,确实是非标准的,最好使用sprintf(target_string,"%d",source_int)or (更好,因为它可以避免缓冲区溢出)snprintf(target_string, size_of_target_string_in_bytes, "%d", source_int)。我知道它不像 那样简洁或酷itoa(),但至少你可以编写一次,到处运行 (tm) ;-)
Here's the old (edited) answer
这是旧的(编辑过的)答案
You are correct in stating that the default gcc libcdoes not include itoa(), like several other platforms, due to it not technically being a part of the standard. See herefor a little more info. Note that you have to
您说默认gcc libc不包含是正确的itoa(),就像其他几个平台一样,因为它在技术上不是标准的一部分。请参阅此处了解更多信息。请注意,您必须
#include <stdlib.h>
Of course you already know this, because you wanted to useitoa()on Linux after presumably using it on another platform, but... the code (stolen from the link above) would look like:
当然,你已经知道这一点,因为你想使用itoa()大概使用它在其他平台上后,在Linux上,但...代码(从上面的链接被盗)将如下所示:
Example
例子
/* itoa example */
#include <stdio.h>
#include <stdlib.h>
int main ()
{
int i;
char buffer [33];
printf ("Enter a number: ");
scanf ("%d",&i);
itoa (i,buffer,10);
printf ("decimal: %s\n",buffer);
itoa (i,buffer,16);
printf ("hexadecimal: %s\n",buffer);
itoa (i,buffer,2);
printf ("binary: %s\n",buffer);
return 0;
}
Output:
输出:
Enter a number: 1750 decimal: 1750 hexadecimal: 6d6 binary: 11011010110
Enter a number: 1750 decimal: 1750 hexadecimal: 6d6 binary: 11011010110
Hope this helps!
希望这可以帮助!
回答by Matt J
As Matt J wrote, there is itoa, but it's not standard. Your code will be more portable if you use snprintf.
正如马特 J 所写,有itoa,但它不是标准的。如果您使用snprintf.
回答by m_pGladiator
I have used _itoa(...) on RedHat 6 and GCC compiler. It works.
我在 RedHat 6 和 GCC 编译器上使用过 _itoa(...)。有用。
回答by James Antill
If you are calling it a lot, the advice of "just use snprintf" can be annoying. So here's what you probably want:
如果您经常调用它,“只使用 snprintf”的建议可能会很烦人。所以这就是你可能想要的:
const char *my_itoa_buf(char *buf, size_t len, int num)
{
static char loc_buf[sizeof(int) * CHAR_BITS]; /* not thread safe */
if (!buf)
{
buf = loc_buf;
len = sizeof(loc_buf);
}
if (snprintf(buf, len, "%d", num) == -1)
return ""; /* or whatever */
return buf;
}
const char *my_itoa(int num)
{ return my_itoa_buf(NULL, 0, num); }
回答by Archana Chatterjee
You can use this program instead of sprintf.
您可以使用此程序代替 sprintf。
void itochar(int x, char *buffer, int radix);
int main()
{
char buffer[10];
itochar(725, buffer, 10);
printf ("\n %s \n", buffer);
return 0;
}
void itochar(int x, char *buffer, int radix)
{
int i = 0 , n,s;
n = s;
while (n > 0)
{
s = n%radix;
n = n/radix;
buffer[i++] = '0' + s;
}
buffer[i] = 'char *itoa(long n)
{
int len = n==0 ? 1 : floor(log10l(labs(n)))+1;
if (n<0) len++; // room for negative sign '-'
char *buf = calloc(sizeof(char), len+1); // +1 for null
snprintf(buf, len+1, "%ld", n);
return buf;
}
';
strrev(buffer);
}
回答by mmdemirbas
Following function allocates just enough memory to keep string representation of the given number and then writes the string representation into this area using standard sprintfmethod.
以下函数分配刚好足够的内存来保留给定数字的字符串表示,然后使用标准sprintf方法将字符串表示写入该区域。
char *num_str = itoa(123456789L);
// ...
free(num_str);
Don't forget to freeup allocated memory when out of need:
不要忘记在free不需要时增加分配的内存:
std::string itos(int n)
{
const int max_size = std::numeric_limits<int>::digits10 + 1 /*sign*/ + 1 /*0-terminator*/;
char buffer[max_size] = {0};
sprintf(buffer, "%d", n);
return std::string(buffer);
}
N.B. As snprintf copies n-1 bytes, we have to call snprintf(buf, len+1, "%ld", n) (not just snprintf(buf, len, "%ld", n))
注意当 snprintf 复制 n-1 个字节时,我们必须调用 snprintf(buf, len+1, "%ld", n) (不仅仅是 snprintf(buf, len, "%ld", n))
回答by Mark Ransom
Edit:I just found out about std::to_stringwhich is identical in operation to my own function below. It was introduced in C++11 and is available in recent versions of gcc, at least as early as 4.5 if you enable the c++0x extensions.
编辑:我刚刚发现std::to_string以下操作与我自己的功能相同。它是在 C++11 中引入的,并且在最新版本的 gcc 中可用,如果启用 c++0x 扩展,则至少早在 4.5 中。
itoaitoagcc
不仅缺少它,而且它不是最方便使用的功能,因为您需要为其提供缓冲区。我需要一些可以在表达式中使用的东西,所以我想出了这个: char* itoah(long num, char* s, int len)
{
long n, m = 16;
int i = 16+2;
int shift = 'a'- ('9'+1);
if(!s || len < 1)
return 0;
n = num < 0 ? -1 : 1;
n = n * num;
len = len > i ? i : len;
i = len < i ? len : i;
s[i-1] = 0;
i--;
if(!num)
{
if(len < 2)
return &s[i];
s[i-1]='0';
return &s[i-1];
}
while(i && n)
{
s[i-1] = n % m + '0';
if (s[i-1] > '9')
s[i-1] += shift ;
n = n/m;
i--;
}
if(num < 0)
{
if(i)
{
s[i-1] = '-';
i--;
}
}
return &s[i];
}
Ordinarily it would be safer to use snprintfinstead of sprintfbut the buffer is carefully sized to be immune to overrun.
通常使用snprintf而不是使用会更安全,sprintf但缓冲区的大小经过仔细调整以防止溢出。
See an example: http://ideone.com/mKmZVE
查看示例:http: //ideone.com/mKmZVE
回答by the sudhakar
direct copy to buffer : 64 bit integer itoa hex :
直接复制到缓冲区:64 位整数 itoa 十六进制:
static char _numberSystem[] = "0123456789ABCDEF";
static char _twosComp[] = "FEDCBA9876543210";
static void safestrrev(char *buffer, const int bufferSize, const int strlen)
{
int len = strlen;
if (len > bufferSize)
{
len = bufferSize;
}
for (int index = 0; index < (len / 2); index++)
{
char ch = buffer[index];
buffer[index] = buffer[len - index - 1];
buffer[len - index - 1] = ch;
}
}
static int negateBuffer(char *buffer, const int bufferSize, const int strlen, const int radix)
{
int len = strlen;
if (len > bufferSize)
{
len = bufferSize;
}
if (radix == 10)
{
if (len < (bufferSize - 1))
{
buffer[len++] = '-';
buffer[len] = '#define INT_LEN (10)
#define HEX_LEN (8)
#define BIN_LEN (32)
#define OCT_LEN (11)
static char * my_itoa ( int value, char * str, int base )
{
int i,n =2,tmp;
char buf[BIN_LEN+1];
switch(base)
{
case 16:
for(i = 0;i<HEX_LEN;++i)
{
if(value/base>0)
{
n++;
}
}
snprintf(str, n, "%x" ,value);
break;
case 10:
for(i = 0;i<INT_LEN;++i)
{
if(value/base>0)
{
n++;
}
}
snprintf(str, n, "%d" ,value);
break;
case 8:
for(i = 0;i<OCT_LEN;++i)
{
if(value/base>0)
{
n++;
}
}
snprintf(str, n, "%o" ,value);
break;
case 2:
for(i = 0,tmp = value;i<BIN_LEN;++i)
{
if(tmp/base>0)
{
n++;
}
tmp/=base;
}
for(i = 1 ,tmp = value; i<n;++i)
{
if(tmp%2 != 0)
{
buf[n-i-1] ='1';
}
else
{
buf[n-i-1] ='0';
}
tmp/=base;
}
buf[n-1] = '##代码##';
strcpy(str,buf);
break;
default:
return NULL;
}
return str;
}
';
}
}
else
{
int twosCompIndex = 0;
for (int index = 0; index < len; index++)
{
if ((buffer[index] >= '0') && (buffer[index] <= '9'))
{
twosCompIndex = buffer[index] - '0';
}
else if ((buffer[index] >= 'A') && (buffer[index] <= 'F'))
{
twosCompIndex = buffer[index] - 'A' + 10;
}
else if ((buffer[index] >= 'a') && (buffer[index] <= 'f'))
{
twosCompIndex = buffer[index] - 'a' + 10;
}
twosCompIndex += (16 - radix);
buffer[index] = _twosComp[twosCompIndex];
}
if (len < (bufferSize - 1))
{
buffer[len++] = _numberSystem[radix - 1];
buffer[len] = 0;
}
}
return len;
}
static int twosNegation(const int x, const int radix)
{
int n = x;
if (x < 0)
{
if (radix == 10)
{
n = -x;
}
else
{
n = ~x;
}
}
return n;
}
static char *safeitoa(const int x, char *buffer, const int bufferSize, const int radix)
{
int strlen = 0;
int n = twosNegation(x, radix);
int nuberSystemIndex = 0;
if (radix <= 16)
{
do
{
if (strlen < (bufferSize - 1))
{
nuberSystemIndex = (n % radix);
buffer[strlen++] = _numberSystem[nuberSystemIndex];
buffer[strlen] = '##代码##';
n = n / radix;
}
else
{
break;
}
} while (n != 0);
if (x < 0)
{
strlen = negateBuffer(buffer, bufferSize, strlen, radix);
}
safestrrev(buffer, bufferSize, strlen);
return buffer;
}
return NULL;
}
note: change long to long long for 32 bit machine. long to int in case for 32 bit integer. m is the radix. When decreasing radix, increase number of characters (variable i). When increasing radix, decrease number of characters (better). In case of unsigned data type, i just becomes 16 + 1.
注意:32位机器把long改成long long。long 到 int 以防 32 位整数。m 是基数。减少基数时,增加字符数(变量 i)。增加基数时,减少字符数(更好)。在无符号数据类型的情况下,我只是变成 16 + 1。
回答by Chris Desjardins
Here is a much improved version of Archana's solution. It works for any radix 1-16, and numbers <= 0, and it shouldn't clobber memory.
这是 Archana 解决方案的改进版本。它适用于任何基数 1-16 和数字 <= 0,并且它不应该破坏内存。
##代码##回答by waaagh
i tried my own implementation of itoa(), it seem's work in binary, octal, decimal and hex
我尝试了我自己的 itoa() 实现,它似乎可以在二进制、八进制、十进制和十六进制中工作
##代码##
