HTML and CSS Reference
In-Depth Information
var color = 0xFF << 16 | 0x55 << 8 | 0xF3;
This sets color to a value of 16733683 , which is equal to the hex value 0xFF55F3 . This formula uses two
bitwise operators you might not have used before. Bitwise operators manipulate numbers on a binary
level—on the ones and zeros. We look at how they work in the next section.
Bitwise combination
If you were to list the bits of a 24-bit color value, you would have a string of 24 ones and zeros. Breaking
up the hex 0xRRGGBB into binary, there are eight bits for red, eight for green, and eight for blue:
RRRRRRRRGGGGGGGGBBBBBBBB
In the previous color combination formula, the first bitwise operator is << , which is the bitwise left-shift
operator. This shifts the binary representation of the value to the left by the specified amount of places. A
red value of 0xFF, or decimal 255, can be represented in binary as follows:
11111111
Shifting it 16 places to the left gives you the following:
111111110000000000000000
As a 24-bit color number, this is red. In hex, this is 0xFF0000—again, red. Now, a green value of 0x55
(decimal 85) looks like the following in binary:
01010101
Shift this eight places, and you get this:
000000000101010100000000
The original eight bits now fall completely in the green range.
Finally, a blue value of 0xF3 (decimal 243) is this in binary:
11110011
Because these bits already fall into the blue range, you don't need to change it.
Now you have three values for red, green, and blue:
111111110000000000000000
000000000101010100000000
000000000000000011110011
You can add the values together to get a single 24-bit number, but there's a simpler way: Use the bitwise
OR operator, the | symbol. This compares the digits of two numbers on a binary level and if either digit is
equal to one, the result will be one. If both digits are zero, the result is zero. You can use OR for the red,
green, and blue values together to say, “If this OR this OR this is one, the result is one.” This joins the
three components into a single color value—and is readable once you understand how the operators work.
Combine the example values and you get this result:
 
Search WWH ::




Custom Search