How do Bitwise Operators work?

只愿长相守 提交于 2021-02-05 11:49:27

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/41667340/how-do-bitwise-operators-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!