Bitwise Operators

Buy or Subscribe

You can access this course in just a minute, and support my efforts to rid the world of crappy online courses!

Buy Standalone  Subscribe

All of the logic gates we've been using (AND, XOR, OR, etc) are part of every programming languages as bitwise operators. You've probably seen them before - here they are in JavaScript:

  • & is AND
  • || is OR
  • ^ is XOR

And so on. In this video we dive in head-first and answer a pretty common interview question:

Create a routine that adds two positive integers together without using mathematic operators.

I got asked this once and drew a complete blank as I had no idea and let the interviewer know that. They tried to offer me clues but I was beyond any kind of help, in a completely foreign land. I knew absolutely nothing about binary!

If this is you, buckle up cause here we go!

The Code

Here's the code we'll be cycling on for the video:

const add =function(x,y) {
  //iterate until there is no carry
  let should_carry = null;
  while(should_carry !== 0){
    should_carry = x & y;
    x = x ^ y;
    y = should_carry << 1;
  }
  return x;
}
console.log(add(27,15));