Hexadecimal and overloading

Hi. I am trying to add two hexadecimals using the addition operator.
I thought I am doing it right, but seems like I am lost.

Please help.

This is where I convert then in another function

convert_Red = strtol(red.c_str(), NULL, 16);
convert_Green = strtol(green.c_str(),NULL, 16);
convert_Blue = strtol(blue.c_str(), NULL, 16);

after this, I try to add the red together, green together and blue together.

This is how i try to do it

HexColour HexColour :: operator+(const HexColour& other) const

int Red = this->convert_Red + other.convert_Red;
int Green = this->convert_Green + other.convert_Green;
int Blue = this->convert_Blue + other.convert_Blue;

ostringstream str;
string name;
str << Red << Green << Blue;




hex >> str;

name = str.str();


HexColour c(name);

return c;
}

Last edited on
You don't tell the interface of HexColour, so we don't tell where you have lost yourself.

name will contain decimal stuff. If the constructor expects hex, then you should tell the stream to make hex.

It could be convenient to construct a HexColour from integer components rather than string.


Is it logical to add colours like that? Let say, I have almost black -- each component is 0x01 (assuming 0xff is max). Add that colour a thousand times and each component becomes 0x3e8, which is way brighter than pure white.
The colours only contain 8 digits.red, blue and green.
e.g 0x113355 and 0x88BBFF should give me 0x99EEFF.

So I was trying to convert to int, add them and then convert them back to hexadecimal. as shown above.
As you can see I already converted them into integers.So I am trying to add them and then after convert them back to hexadecimal.Please help.I am clearly missing something
http://www.cplusplus.com/reference/ios/hex/

Your HexColour has the three integers. Would it not be more efficient to operate primarily with the integers and produce the string only when necessary?

If 55+FF must equal FF, then you need to clamp the result to FF. c = (a + b) % 256;
Thanxs.got it right.The problem was with this statement str << hex << name;
Topic archived. No new replies allowed.