Blog

Bitwise Operators for everyone

Bitwise operators in JavaScript might seem like a foreign language at first, but let’s break it down into simpler terms.

Imagine you’ve got a string of small fairy lights. Each one can be either shining bright (1) or switched off (0). This is what we call binary code. The computer uses this binary code to understand everything – every number, every letter, absolutely everything is converted into this language of 1s and 0s inside a computer.

Now, JavaScript’s bitwise operators are like little wizards that can change these strings of lights (or binary numbers).

Let’s take 10 and 13 as an example. In the language of computers (binary), 10 is 1010 and 13 is 1101.

We’ve got 5 main wizards (or bitwise operators):

Bitwise AND (&): This wizard only lights up a bulb if both corresponding bulbs from the two numbers are shining. So, when you say 10 & 13, it translates to 1000 (or 8 in our everyday numbers), because the only position where both 10 and 13 have their lights on is the third one from the right.

Bitwise OR (|): This wizard lights up a bulb if at least one of the corresponding bulbs from the two numbers is shining. So, when you say 10 | 13, it translates to 1101 (or 13 in our everyday numbers), because the only position where both 10 and 13 have their lights off is the fourth one from the right.

Bitwise XOR (^): This wizard is a bit of a character. It only lights up a bulb if exactly one of the corresponding bulbs is shining, but not both. So, when you say 10 ^ 13, it translates to 0111 (or 7 in our everyday numbers), because in the third position from the right, both bulbs are on, so the XOR operator switches that bulb off.

Bitwise NOT (~): This operator is the rebel of the group, it just flips the state of all bulbs. If a bulb is on, it switches it off. If it’s off, it switches it on. So when you say ~10, it translates to -11, because it switches every bulb in the binary representation of 10, and in computers, the extra bulb on the left that got switched on indicates that the number is negative.

We also have shift operators (<<, >>, >>>) that slide the bulbs left or right. Think of it as everyone in the line taking a step to the left or right.

While bitwise operators are quick and often used in coding challenges and games, they’re not as common in regular programming. So don’t fret if they seem a bit unusual now. You’ll get the hang of it with practice!

Bitwise operators are often used in scenarios where low-level manipulation of numbers is required. While their use in high-level JavaScript applications like those built with React or Node.js is somewhat rare, there are cases where they might help with speed optimizations.

Left and Right Shift Operator

Imagine you have a line of toy blocks. Some blocks are red, and some are blue. You also have a magic wand that you can use to command these blocks to shuffle left or right.

When you use the “<<” operator, it’s like you’re waving your magic wand and yelling “Scoot to the left!”. Every block obediently steps to the left. The block at the far left tumbles off the end and is replaced by a new block (which is always blue) at the right end.

Now, when you use the “>>” operator, you’re waving your wand and shouting “Slide to the right!”. This time, all the blocks shuffle to the right. The block at the far right topples off the end, and a new block takes its place at the left end. If the first block was red, a new red block appears; if it was blue, a blue one takes its place.

In the realm of computers, these blocks represent bits, which are the tiniest pieces of data. They can either be a 0 (like our blue blocks) or a 1 (like our red blocks). When we use these operators, we’re telling these bits to scoot left or right. This action can alter the number that these bits represent.

Just keep in mind: “<<” is your command for left, “>>” for right, and you’re the one conducting this block dance with your magic wand!

Here are a couple of examples:

  1. Faster Arithmetic Operations: Bitwise operations are usually faster than arithmetic operations. You can use shift operators (<<, >>) to perform multiplication or division by powers of 2. For example:javascript
let x = 5;
let y = x << 1;  // equivalent to x * 2
let z = x >> 1;  // equivalent to Math.floor(x / 2)

This technique can be more efficient than using regular multiplication or division operations, especially when you’re dealing with a large amount of data.

Checking for Even or Odd Numbers: You can use the bitwise AND operator (&) to quickly check whether a number is even or odd:

javascript
function isEven(num) {
    return (num & 1) === 0;
}

function isOdd(num) {
    return (num & 1) === 1;
}

This can be faster than using the modulus operator (%).

Working with RGB Colors: Bitwise operators can be used to extract or manipulate the red, green, and blue channels of a color. This is useful when you’re working with Canvas or WebGL in JavaScript:

javascript
let color = 0x123456;  // some color in hexadecimal (RGB)
let red = (color >> 16) & 0xFF;
let green = (color >> 8) & 0xFF;
let blue = color & 0xFF;

Efficient Storage with Flags: Bitwise operators can be used to store multiple Boolean values within a single number, which can be more memory efficient. This can be useful in scenarios where you need to keep track of a large set of binary states or flags:

const FLAG_A = 1;  // 001 in binary
const FLAG_B = 2;  // 010 in binary
const FLAG_C = 4;  // 100 in binary

let flags = FLAG_A | FLAG_B;  // turn on flags A and B

// Check if a flag is on
if (flags & FLAG_A) {
    console.log('Flag A is on');
}

Please note that while bitwise operations can be faster in some scenarios, the speed difference may not be significant in high-level applications due to JavaScript engine optimizations. Always prioritize code readability and maintainability over micro-optimizations.

How useful was this post?

Click on a heart to rate it!

Average rating 0 / 5. Vote count: 0

No votes so far! Be the first to rate this post.

Leave a Reply