Question

How can i convert an integer ranging from 0 to 255 to a string with exactly two chars, containg the hexadecimal representation of the number?

Example

input: 180 output: "B4"

My goal is to set the grayscale color in Graphicsmagick. So, taking the same example i want the following final output:

"#B4B4B4"

so that i can use it for assigning the color: Color("#B4B4B4");

Should be easy, right?

Was it helpful?

Solution

You don't need to. This is an easier way:

ColorRGB(red/255., green/255., blue/255.)

OTHER TIPS

You can use the native formatting features of the IOStreams part of the C++ Standard Library, like this:

#include <string>
#include <sstream>
#include <iostream>
#include <ios>
#include <iomanip>

std::string getHexCode(unsigned char c) {

   // Not necessarily the most efficient approach,
   // creating a new stringstream each time.
   // It'll do, though.
   std::stringstream ss;

   // Set stream modes
   ss << std::uppercase << std::setw(2) << std::setfill('0') << std::hex;

   // Stream in the character's ASCII code
   // (using `+` for promotion to `int`)
   ss << +c;

   // Return resultant string content
   return ss.str();
}

int main() {
   // Output: "B4, 04"
   std::cout << getHexCode(180) << ", " << getHexCode(4); 
}

Live example.

Using printf using the %x format specifier. Alternatively, strtol specifying the base as 16.

#include<cstdio>

int main()
{

    int a = 180;
    printf("%x\n", a);

    return 0;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top