I have the following:

typedef union
{
    unsigned Color;
    struct
    {
        unsigned char B, G, R, A;
    };
} RGB, *PRGB;

Then I have:

RGB Rgb(XYZ Xyz)
{
    RGB Result;
    double X = Xyz.X / 100;
    double Y = Xyz.Y / 100;
    double Z = Xyz.Z / 100;

    double Red = X * 3.2406 + Y * -1.5372 + Z * -0.4986;
    double Green = X * -0.9689 + Y * 1.8758 + Z * 0.0415;
    double Blue = X * 0.0557 + Y * -0.2040 + Z * 1.0570;

    Red = (Red > 0.0031308) ? (1.055 * pow(Red, (1/2.4)) - 0.055) : 12.92 * Red;
    Green = (Green > 0.0031308) ? (1.055 * pow(Green, (1/2.4)) - 0.055) : 12.92 * Green;
    Blue = (Blue > 0.0031308) ? (1.055 * pow(Blue, (1/2.4)) - 0.055) : 12.92 * Blue;

    //Printing Red here and blue here are perfectly fine..
    //The problem is here..
    Result.R = (unsigned char)round(Red * 255);
    Result.G = (unsigned char)round(Green * 255);
    Result.B = (unsigned char)round(Blue * 255);

    return Result;
}

In that function above, my values overflow even though I rounded it. When printed, it prints random values which I know is an overflow.
If I change all the doubles to floats, it works perfectly fine and prints the correct value every time. Why? How can I keep it as double? Or should I just change it all to float? I wanted double because it holds more decimal places..

A double takes up 64bits in memory (usually) you can find the specifics for your machine by using the sizeof() operator in C++. A float takes 32bits, again usually. Where an unsigned char has 8, meaning 256 values. If your round was above 255, it would cause your overflow. I would just use floats, as they are faster to process, and still probably hold all the values you could possibly need (+/-3.4028234E38, depending on the number of bits)

As a side note, check out lines 4-6 if Xyz.X/Xyz.Y/Xyz.Z are ints, your division will not work as expected, as it would be doing integer math, meaning 99 / 100 = 0 not .99, to do that use

double X = Xyz.X / 100.0;

Ahh the 100.0 solved it. It works with doubles as long as I have the trailing decimal. Without that it overflows. I checked the values via cout before the function returns and they were all less than 255. Just happened to be the decimal. Figured that out after googling for hours last night lol. Thank you though. +Rep.

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.