Skip to content

Instantly share code, notes, and snippets.

@jaydg
Last active June 10, 2018 20:00
Show Gist options
  • Save jaydg/f4fad796c4b2ddf2f786872af5c29150 to your computer and use it in GitHub Desktop.
Save jaydg/f4fad796c4b2ddf2f786872af5c29150 to your computer and use it in GitHub Desktop.
Hex <-> RGB color conversion
module hex2rgb;
struct RGB {
ubyte r;
ubyte g;
ubyte b;
public this(ubyte r, ubyte g, ubyte b) {
this.r = r;
this.g = g;
this.b = b;
}
public this(string strval) {
import std.conv : to;
assert(strval.length == 7);
int value = to!int(strval[1..7], 16);
this.r = (value & 0xff0000) >> 16;
this.g = (value & 0x00ff00) >> 8;
this.b = (value & 0x0000ff);
}
string toString() {
import std.string : format;
return format("#%06x", (this.r << 16) + (this.g << 8) + this.b);
}
}
unittest {
assert(RGB(0, 51, 255).toString == "#0033ff");
assert(RGB("#0033ff") == RGB(0, 51, 255));
assert(RGB("#ffffff") == RGB(255, 255, 255));
assert(RGB("#999999") == RGB(153, 153, 153));
}
version (unittest) {
void main() {};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment