J Stephan
J Stephan

Reputation: 93

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

Upvotes: 1

Views: 1675

Answers (4)

Sudhakar Singh
Sudhakar Singh

Reputation: 389

use sprintf

int i = 100;

char str[5];

sprintf(str, "%d", i);

Upvotes: 2

Vilx-
Vilx-

Reputation: 107052

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.

Upvotes: 5

Armen Tsirunyan
Armen Tsirunyan

Reputation: 133122

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

Upvotes: 1

Senthil Kumaran
Senthil Kumaran

Reputation: 56951

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();

Upvotes: 1

Related Questions