Skip to content

Instantly share code, notes, and snippets.

@ahmadalibaloch
Created October 11, 2019 11:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ahmadalibaloch/d73c4144b0dcb28206c60a174c8a99a9 to your computer and use it in GitHub Desktop.
Save ahmadalibaloch/d73c4144b0dcb28206c60a174c8a99a9 to your computer and use it in GitHub Desktop.
RGB to HEX and HEX to RGB color conversion in Javascript - using shift operators
function rgbToHex([red = 0, green = 0, blue = 0] = []) {
// Left shift (<<) operator for color conversion is interesting
// the color value for each component of an RGB color is between 0 - 255 (8bits)
// The first 8 bits starting from the right will represent the blue component,
// the next 8 bits will represent the green component, and the 8 bits after that will represent the red component
return `#${(red << 16 | green << 8 | blue).toString(16)}`;
}
function hexToRgb(hex) {
// working through above shift operator procedure backwards
// we will right-shift the color bits by multiples of 8 as necessary until
// we get the target component bits as the first 8 bits from the right
hex = hex.replace(/^#?([0-9a-f]{6})$/i, '$1');
hex = Number(`0x${hex}`);
// we need a way to mask out every other bits except the first 8 bits.
// & operator can be used to ensure that certain bits are turned off.
return [
hex >> 16 & 0xff, // red
hex >> 8 & 0xff, // green
hex & 0xff // blue
];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment