RGB to Hex and Hex to RGB

How to convert colors in RGB format to Hex format and vice versa?

For example, convert '#0080C0' to (0, 128, 192) .


interface RGB {
  r: number;
  g: number;
  b: number;
}

class ColorService {
  rgbToHex(rgb: RGB): string {
     return "#" + (
      (1 << 24) + // to get leading zeroes on r if needed
      (rgb.r << 16) + (rgb.g << 8) + rgb.b)
      .toString(16) // hexify
      .slice(1); // and strip off that artificial '1' we put on the front
  }

  hexToRgb(hex: string): RGB {
    hex = hex.replace(/^#/, "");
    // support short-version with one nybble per chroma by expanding 'x' to 'xx'
    hex = hex.length === 3 ? hex.replace(/(.)/g, "$1$1") : hex;

    return {
      r: parseInt(hex.substr(0, 2), 16) / 255,
      g: parseInt(hex.substr(2, 2), 16) / 255,
      b: parseInt(hex.substr(4, 2), 16) / 255
    };
  }
}
1 Like