How can I convert Hexadecimal to RGB Color and vice-versa?

Jacob Carlborg doob at me.com
Tue Nov 24 10:31:04 UTC 2020


On Friday, 16 October 2020 at 20:10:58 UTC, Marcone wrote:
> How can I convert Hexadecimal to RGB Color and vice-versa?

Not sure if this is what you're looking for:

struct Color
{
     private uint hex;

     int red()
     out(result; result >= 0 && result <= 255) // assert that the 
result is within bounds
     {
         return (hex & 0xFF0000) >> 16;
     }

     void red(int value)
     in(value >= 0 && value <= 255) // assert that the value is 
within bounds
     {
         hex = (hex & 0x00FFFF) | (value << 16);
     }

     int green()
     out(result; result >= 0 && result <= 255) // assert that the 
result is within bounds
     {
         return (hex & 0x00FF00) >> 8;
     }

     void green(int value)
     in(value >= 0 && value <= 255) // assert that the value is 
within bounds
     {
         hex = (hex & 0xFF00FF) | (value << 8);
     }

     int blue()
     out(result; result >= 0 && result <= 255) // assert that the 
result is within bounds
     {
         return hex & 0x0000FF;
     }

     void blue(int value)
     in(value >= 0 && value <= 255) // assert that the value is 
within bounds
     {
         hex = (hex & 0xFFFF00) | value;
     }

     string toString()
     {
         return format!"Color(red: %s, green: %s, blue: %s)"(red, 
green, blue);
     }
}

void main()
{
     Color color;
     color.red = 255;
     color.green = 143;
     color.blue = 89;

     writeln(color);
}

--
/Jacob Carlborg


More information about the Digitalmars-d-learn mailing list