1

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 like Linux, suse. Any suggestion for using itoa in open source environment.

J Stephan
  • 93
  • 8

4 Answers4

5

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 function atoi.

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.
Vilx-
  • 104,512
  • 87
  • 279
  • 422
2

use sprintf

int i = 100;

char str[5];

sprintf(str, "%d", i);
Sudhakar Singh
  • 389
  • 7
  • 19
  • 1
    str should probably be around 12 characters long if it is to hold any sized integer. Also prefer snprintf to sprintf – doron Dec 29 '10 at 11:32
1

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();
Senthil Kumaran
  • 54,681
  • 14
  • 94
  • 131
1

itoa isn't a standard C++ function. Use boost::lexical_cast, or use stringstreams

Armen Tsirunyan
  • 130,161
  • 59
  • 324
  • 434