On 10/16/20 1:10 PM, Marcone wrote:
How can I convert Hexadecimal to RGB Color and vice-versa?

On 10/16/20 1:10 PM, Marcone wrote:

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

Do you mean from a string like "#123456" to the values of red, green, and blue? I am having more fun with D than usual. So, I wrote the following without understanding your requirements. :)

I am sure this already exists in various libraries.

import std.exception;
import std.range;
import std.format;
import std.stdio;
import std.traits;

struct RGB {
  ubyte red;
  ubyte green;
  ubyte blue;

  this(const(char)[] s) {
    enforce(s.length < 8, format!`Invalid RGB string: "%s"`(s));

    if (s.front == '#') {
      s.popFront();
    }

     uint value;
     s.formattedRead!"%x"(value);
     this(value);
  }

  this(T)(T value)
  if (isIntegral!T) {
    enforce(value >= 0 && value < 0x100_0000,
format!"Invalid RGB value: %s (0x%,*?x)"(value, 2, '_', value));

    ubyte popLowByte() {
      ubyte b = value & 0xff;
      value >>= 8;
      return b;
    }

    this.blue = popLowByte();
    this.green = popLowByte();
    this.red = popLowByte();

    assert(value == 0);
  }

  string asHex() {
    return format!"%02x%02x%02x"(red, green, blue);
  }
}

void main() {
  auto a = RGB("#a0a0a0");
  writeln(a);

  auto b = RGB(0x10ff20);
  writeln(b);
  writeln(b.asHex);
}

Ali

Reply via email to