I have this:

int serialInt = 40000359;

but what I really need is this:

int serialHex = (int)0x40000359;

What can I do to turn serialInt into serialHex?

I found some code that claimed to do this:

int IntToHex(int input)
{
  std::stringstream ss;
  for (int i=2*sizeof(int) - 1; i >= 0; i--)
  {
    ss << "0123456789ABCDEF"[((input >> i*4) & 0xF)];
  }
  int output;
  ss >> output;
  return output;
}

but the result is incorrect. The output of:

std::cout << "Correct: " << (int)0x000040000359 << std::endl;
  int serial = 40000359;
  int serialHex = IntToHex(serial);
  std::cout << "Serial converted to hex: " << serialHex << std::endl;

is

Correct: 1073742681
Serial converted to hex: 2625

Any thoughts on a better way to do this?

Thanks,

David

Just convert the int to a string and add "0x" to the beginning of the string

int serial = 40000359;
char result[20];
sprintf(result,"0x%d", serial);

Or if you want to use only c++

#include <sstream> 
#include <string>
#include <iostream>

int main()
{
   int serial = 40000359;
   std::string result;
   std::stringstream str;
   str << "0x" << serial;
   str >> result;
   std::cout << result << '\n';
}

Sounds like a good plan.. but how do you get it back into an int? I tried this:

#include <iostream>
#include <sstream>

int IntToHex(int input);

int main(int argc, char* argv[])
{
  int serial = 40000359;
  int serialHex = (int)0x40000359;
  int convertedSerial = IntToHex(serial);

  std::cout << serialHex << std::endl;
  std::cout << convertedSerial << std::endl;

  return 0;
}


int IntToHex(int input)
{
  std::stringstream ss;
  std::string result;
  ss << "0x" << input;
  int output;
  ss >> output;
  
  return output;
}

but the return value is 0.

David

You have to tell stringstream that the string is in hex fomat ss >> std::hex >> output; And include <iomanip>

Awesome, works like a charm, thanks. FYI I didn't have to include <iomanip>, I guess it gets included by sstream?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.