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?
If you just want to print them:
i tried my own implementation of itoa(), it seem's work in binary, octal, decimal and hex
EDIT: Sorry, I should have remembered that this machine is decidedly non-standard, having plugged in various non-standard
libc
implementations for academic purposes ;-)As
itoa()
is indeed non-standard, as mentioned by several helpful commenters, it is best to usesprintf(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 asitoa()
, but at least you can Write Once, Run Everywhere (tm) ;-)Here's the old (edited) answer
You are correct in stating that the default
gcc libc
does not includeitoa()
, like several other platforms, due to it not technically being a part of the standard. See here for a little more info. Note that you have toOf course you already know this, because you wanted to use
itoa()
on Linux after presumably using it on another platform, but... the code (stolen from the link above) would look like:Example
Output:
Hope this helps!
If you are calling it a lot, the advice of "just use snprintf" can be annoying. So here's what you probably want:
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
sprintf
method.Don't forget to
free
up allocated memory when out of need: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))
direct copy to buffer : 64 bit integer itoa hex :
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.