C++ int to binary
I am using itoa builtin function, in order to convert an integer into binary and store it in char*. Every thing works fine and output is also correct (as expected). The only thing which goes wrong is that itoa doesn't work on open source lik开发者_运维技巧e Linux, suse. Any suggestion for using itoa in open source environment.
To cite Wikipedia:
The
itoa
(integer to ASCII) function is a widespread non-standard extension to the standard C programming language. It cannot be portably used, as it is not defined in any of the C language standards; however, compilers often provide it through the header<stdlib.h>
while in non-conforming mode, because it is a logical counterpart to the standard library functionatoi
.
In other words:
- First check your compiler options, maybe you can force it to recognize this;
- If that fails, either use one of the workarounds suggested by others, or just plain write it yourself. It's pretty trivial.
use sprintf
int i = 100;
char str[5];
sprintf(str, "%d", i);
itoa is non-standard function. You can get the behavior similar to itoa using stringstream
#include<sstream>
string a;
int i;
stringstream s;
s << i;
a = s.str();
itoa
isn't a standard C++ function. Use boost::lexical_cast
, or use stringstreams
精彩评论