views:

142

answers:

6

C/C++ equivalent to java Integer.toHexString.

Porting some code from java to C/C++, does C have a build in function to Integer.toHexString in java?

UPDATE:

Heres is the exact code i'm trying to port:

String downsize = Integer.toHexString(decimal);
+5  A: 

In C:

sprintf(s, "%x", value);

Be sure to have enough space at s for rendering of the hex number. 64 bytes are guaranteed (hereby) to be enough.

Pavel Radzivilovsky
You should use `snprintf` instead of `sprintf` because the latter can overflow the buffer.
R Samuel Klatchko
In case your compiler supports it. MSVC still doesn't support C99, afaik.
Pavel Radzivilovsky
Microsoft has their own solution (StrSafe). If you're dealing with `TCHAR`s that's probably the way to go. If, on the other hand, you actually know whether you're dealing with `char`s or `wchar_t`s (and, by extension, the encoding you're using) then you can use something more standardized.
Max Lybbert
Please, don't ever use TCHAR..
Pavel Radzivilovsky
+4  A: 

How about Boost.Format for a C++ solution:

(format("%X") % num).str()
Ryan Ginstrom
+8  A: 

Using the <sstream> header:

std::string intToHexString(int i) {
    std::stringstream ss;
    ss << std::hex << std::showbase << i;
    return ss.str();
}
Gunslinger47
+1  A: 
#include <iostream>
#include <sstream>

std::stringstream ss(std::stringstream::out);
int i;
ss << std::hex << i << flush;
string converted = ss.str();

Also take a look at setw (which needs #include <iomanip>)

Ben Voigt
A: 

itoa does what you want (third param denotes base):

/* itoa example */
#include <stdio.h>
#include <stdlib.h>

int main ()
{
  int i = 12;
  char buffer [33];
  itoa (i,buffer,16);
  printf ("hexadecimal: %s\n",buffer);
  return 0;
}
Schmoo
Why non-standard function?
Nyan
+3  A: 

char s[1+2*sizeof x]; sprintf(s, "%x", x);

R..