Question

I am using a "LightenDarkenColor" function in my script and never really paid much attention to it until now and I noticed some operations and I had no idea what they were doing. I had actually never seen them before.

Those operators are >> and &. I also noticed that the function doesn't work in Firefox.

The function:

function LightenDarkenColor(color, percent) {

        var num = parseInt(color,16),
            amt = Math.round(2.55 * percent),
            R   = (num >> 16) + amt,
            B   = (num >> 8 & 0x00FF) + amt,
            G   = (num & 0x0000FF) + amt;

        return (0x1000000 + (R<255?R<1?0:R:255)*0x10000 + (B<255?B<1?0:B:255)*0x100 + (G<255?G<1?0:G:255)).toString(16).slice(1);

}

What exactly are the operators and how do they work?

Was it helpful?

Solution

Imagine num is 227733 (= some mild dark green) and take

B   = (num >> 8 & 0x00FF)

num >> 8 will shift the number (move digits) to the right by 2 hex digits (4 bits per digit x 2=8) making it become:

227733 => 002277

then & 0x00FF will clear out all digits except the last two

002277 => 000077

and that is the component for green.

Hex 00FF is binary 0000000011111111 and & (binary AND) is the operation that will compare all bit pairs one by one and set all bits to zero unless both operand bits are 1s. So ANDing to zeroes will lead to zeroes, and ANDing to ones will give as result the same digits of the other operand: 1 & 1 => 1, 0 & 1=>0. Ones remain ones, zeroes remain zeroes. So AnyNumber & 0000000011111111 = the right part (lower 2 digits) of AnyNumber.

It is just the standard way of getting a number subpart. In this case the green component. Shift right to clear the lower bits, and &0000...1111 to clear the upper bits.


After it got all color components, it adds amt to all of them (amt positive=lighter) and at the end it crops the values

R<255?R<1?0:R:255 means: if less then 0 use 0, if more than 255 use 255.

And finally restores the color as a single number (instead of *0x100 could have used R<<8 that is the opposite of >>8, instead of +, it could have used |, binary OR, to merge the components).


Note that the function uses B as the second component, assuming it is blue but in reality in RGB the second is Green. Yet the result is correct anyway (it would work whatever color components you used and however you named them)

OTHER TIPS

They're bitwise operators.

>> is a bitwise (Sign-propagating) right shift,

& is a bitwise "and".

I could go into detail on what these operators do, but the MDN has a good explanation and example for each operator. It would be counter-productive to copy those.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top