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)
?
相关问题
- Multiple sockets for clients to connect to
- Is shmid returned by shmget() unique across proces
- What is the best way to do a search in a large fil
- glDrawElements only draws half a quad
- how to get running process information in java?
There is no such function in Linux. I use this code instead.
I have used _itoa(...) on RedHat 6 and GCC compiler. It works.
As
itoa()
is not standard in C, various versions with various function signatures exists.char *itoa(int value, char *str, int base);
is common in *nix.Should it be missing from Linux or if code does not want to limit portability, code could make it own.
Below is a version that does not have trouble with
INT_MIN
and handles problem buffers:NULL
or an insufficient buffer returnsNULL
.Below is a C99 or later version that handles any base [2...36]
For a C89 and onward compliant code, replace inner loop with
Edit: I just found out about
std::to_string
which 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.Not only is
itoa
missing from gcc, it's not the handiest function to use since you need to feed it a buffer. I needed something that could be used in an expression so I came up with this:Ordinarily it would be safer to use
snprintf
instead ofsprintf
but the buffer is carefully sized to be immune to overrun.See an example: http://ideone.com/mKmZVE
Reading the code of guys who do it for a living will get you a LONG WAY.
Check out how guys from MySQL did it. The source is VERY WELL COMMENTED and will teach you much more than hacked up solutions found all over the place.
MySQL's implementation of int2str
I provide the mentioned implementation here; the link is here for reference and should be used to read the full implementation.
itoa
is not a standard C function. You can implement your own. It appeared in the first edition of Kernighan and Ritchie's The C Programming Language, on page 60. The second edition of The C Programming Language ("K&R2") contains the following implementation ofitoa
, on page 64. The book notes several issues with this implementation, including the fact that it does not correctly handle the most negative numberThe function
reverse
used above is implemented two pages earlier: