按位运算符如何工作? [英] How do Bitwise Operators work?

查看:61
本文介绍了按位运算符如何工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我在codewars.com遇到了一些问题,并且遇到了有关基本加密的问题(

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
};

全部是因为添加了该&255 ,有人可以通过添加使我的代码有效的方法来向我解释真正的变化吗?

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

推荐答案

如上所述,您的有效字符范围是0到255.有许多方法可以验证此条件,但按位和看起来最短.

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.

按位与在每个操作数对应的位为1的每个位位置返回1.

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

例如:

1111&0000 将返回 0000

1111&0001 将返回 0001

1111&0010 将返回 0010

1111&0100 将返回 0100

但是,正如您可以在文档中看到的那样:

But, as you can read in the docs:

按位运算符在这种二进制表示形式上执行其操作,但是它们返回标准的JavaScript数值.

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.

在您的情况下,请使用 number&255 可确保最终值在0到255之间.

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.

这篇关于按位运算符如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆