# Bitwise Operators
The Bitwise operators allow us to use JavaScript and work with numbers at the binary level.
# The Bitwise AND operator
& - binary AND operator
The binary & operator is used to AND two numbers at the binary level
11001010
& 00001111 //the result of this is 00001010
2
For each bit we compare the matching positions if both are a 1 then the result in that position is 1.
# The Bitwise Shift Operators
Sometimes we want to trim off the last few digits of a binary number or we want to add some more digits. The shift operators let us do that. The best example of this is when we want to extract the red, green, and blue parts of a colour value.
Hex colours are made up of three values 00-FF
, 00-FF
, and 00-FF
. Each one is a number between 0 and 255.
In binary, 255 is 11111111
. That is 8 ones. So, for each colour there are 8 bits. The colour white is (255, 255, 255) or #FFFFFF
.
In binary white would be 11111111 11111111 11111111
. That is why Jpegs are called 24 bit images. Each pixel is a colour made up of 24 bits. Black would be represented by 24 zeroes - 00000000 00000000 00000000
.
If you write 24 ones as a decimal number it is 2 to the power of 24 or 16,777,216.
A random colour would be a value between 0 and 16,777,216.
So, if we had the random number 1,654,344, in binary that would be 00011001 00111110 01001000
. The first 8 bits represent the red colour, the middle 8 bits are the green value, and the last 8 bits are the blue value.
If you want to extract those three parts of the one colour, we will use the shift operator.
For the red colour, we will shift the bits 16 places to the right. Basically, we are stripping off the rightmost 16 bits. Leaving us only the first 8 bits 00011001
. In decimal, that would be - 25.
For the blue colour, we will use the AND operator. We AND the whole number with 255 (or 11111111
). This will make the left most 16 bits zero. Only the 8 right most bits could possibly line up with our 255. The result will be 01001000
or 72.
For the green colour we need to do both things - shift over 8 bits and then AND the right most 8 bits with 11111111
(255). The green portion 00111110
is 62.
So, the RGB version of 00011001 00111110 01001000
is rgb(25, 62, 72).
# Codepen Samples
Here are some CodePens using the Bitwise operators.
# Generating a Random Colour, Displaying it in RGB with Contrasting Text
# Converting from HEX to decimal numbers for Colours
Codepen calculating Odd and Even - open this one in a new page and open the development tools console to see the results.
A practical use for Bitwise operators, beyond calculating odd or even, is saving user permissions inside a single number.