开发者

C/C++ equivalent to java Integer.toHexString

开发者 https://www.devze.com 2023-01-04 15:58 出处:网络
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?

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:

S开发者_Python百科tring downsize = Integer.toHexString(decimal);


Using the <sstream> header:

std::string intToHexString(int i) {
    std::stringstream ss;
    ss << std::hex << std::showbase << i;
    return ss.str();
}


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

(format("%X") % num).str()


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.


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


#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>)


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;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消