How do Bitwise Operators work?

前端 未结 1 1848
醉话见心
醉话见心 2021-01-28 03: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

相关标签:
1条回答
  • 2021-01-28 03:48

    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.

    0 讨论(0)
提交回复
热议问题