Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@callumlocke
Created July 21, 2015 13:56
Show Gist options
  • Star 10 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save callumlocke/41b210743990f07c2d96 to your computer and use it in GitHub Desktop.
Save callumlocke/41b210743990f07c2d96 to your computer and use it in GitHub Desktop.
RGB colour to single decimal number
// convert three r,g,b integers (each 0-255) to a single decimal integer (something between 0 and ~16m)
function colourToNumber(r, g, b) {
return (r << 16) + (g << 8) + (b);
}
// convert it back again (to a string)
function numberToColour(number) {
const r = (number & 0xff0000) >> 16;
const g = (number & 0x00ff00) >> 8;
const b = (number & 0x0000ff);
return [r, g, b];
// or eg. return `rgb(${r},${g},${b})`;
}
@YingshanDeng
Copy link

there is a mistake.

  const b = (number & 0xff0000) >> 16;
  const g = (number & 0x00ff00) >> 8;
  const r = (number & 0x0000ff);

@vorobeij
Copy link

vorobeij commented Jan 6, 2019

where is alpha?

@izzetseydaoglu
Copy link

where is alpha?

export function number2color(num) {
num >>>= 0;
const b = num & 0xFF,
g = (num & 0xFF00) >>> 8,
r = (num & 0xFF0000) >>> 16,
a = ((num & 0xFF000000) >>> 24) / 255;
return "rgba(" + [ r, g, b, a ].join(",") + ")";
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment