Vikaton
Vikaton

Reputation: 2407

How do Bitwise Operators work?

So I was going through some problems at codewars.com and I came across a problem about basic encryption (https://www.codewars.com/kata/basic-encryption/javascript). The goal is to get a string value and shift it x values to the right on the ASCII chart.

here was my initial solution:

function encrypt(text, rule) {
    let res = ''
  for(let i = 0; i<text.length; i++) {
    res += (String.fromCharCode(text.charCodeAt(i)+rule))
  }
  return res
};

However, it didn't pass all of the tests, so I looked at the solutions and this is what got me to pass the tests:

function encrypt(text, rule) {
    let res = ''
  for(let i = 0; i<text.length; i++) {
    res += (String.fromCharCode(text.charCodeAt(i)+rule & 255))
  }
  return res
};

All because of adding that & 255, Could someone explain to me what has really changed by adding that to make my code valid?

Upvotes: 0

Views: 251

Answers (1)

Mateusz Woźniak
Mateusz Woźniak

Reputation: 1499

As somebody said above, your valid range of characters is from 0 to 255. There are many ways to valid this condition but bitwise and looks like shortest one.

Bitwise AND returns a one in each bit position for which the corresponding bits of both operands are ones.

For example:

1111 & 0000 would return 0000

1111 & 0001 would return 0001

1111 & 0010 would return 0010

1111 & 0100 would return 0100

But, as you can read in the docs:

Bitwise operators perform their operations on such binary representations, but they return standard JavaScript numerical values.

If you use this operator on integer you would get integer instead of binary.

In your case, using number & 255 makes you sure that end value would be in range from 0 to 255.

You can read more about bitwise operators there.

Upvotes: 2

Related Questions