HTML and CSS Reference
In-Depth Information
111111110101010111110011
If you convert that to hex, you get 0xFF55F3. Of course, in JavaScript, you never see the bits or deal with
the ones or zeros at all. You just write this:
var color = 0xFF << 16 | 0x55 << 8 | 0xF3;
Or, if you are working with decimal values, you can use this form:
var color = 255 << 16 | 85 << 8 | 243;
Again, it doesn't matter whether you use hex or decimal numbers; it's the same value.
Extracting component colors
You might have a color from which you want to extract the individual component values. Here's the
formula to extract the red, green, and blue values from a composite color value:
red = color >> 16 & 0xFF;
green = color >> 8 & 0xFF;
blue = color & 0xFF;
If the value of color is 0xFF55F3, then red will be set to 255, green : 85, and blue : 243. Again, this
formula uses two bitwise operators, which we walk through in the next section.
Bitwise extraction
In the previous formula, you probably guessed that >> is the bitwise right-shift operator, which shifts the
bits so many places to the right. You can't have fractional bits, so any bits that are shifted too far right are
discarded. Looking at the color value in binary representation, and beginning with red:
111111110101010111110011
When you shift the color value 16 places to the right, it becomes this:
11111111
This is simply 0xFF, or 255. For green, shift the color value eight places, and you get this:
1111111101010101
Here, you knocked the blue values out, but you still have the red ones hanging around. This is where you
use another bitwise operator, & , which is called AND. Like OR, this compares two values, but says, “If this
digit AND this digit are both one, then the result is one. If either one is zero, the result is zero.” You
compare the value to 0xFF, so you compare these two numbers:
1111111101010101
0000000011111111
Because all the red digits are compared with zero, they all result in zero. Only the digits that are both one
fall through, so you get this:
0000000001010101
 
Search WWH ::




Custom Search