位运算符如何工作?
How do Bitwise Operators work?
所以我在 codewars.com 遇到了一些问题,我遇到了一个关于基本加密的问题 (https://www.codewars.com/kata/basic-encryption/javascript)。目标是获取一个字符串值并将其在 ASCII 图表上向右移动 x 个值。
这是我最初的解决方案:
function encrypt(text, rule) {
let res = ''
for(let i = 0; i<text.length; i++) {
res += (String.fromCharCode(text.charCodeAt(i)+rule))
}
return res
};
但是,它没有通过所有测试,所以我查看了解决方案,这就是让我通过测试的原因:
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
,有人可以向我解释添加它使我的代码有效后真正改变了什么吗?
正如上面有人所说,您的有效字符范围是从 0 到 255。有很多方法可以使这个条件有效,但 bitwise and
看起来是最短的一个。
Bitwise AND returns a one in each bit position for which the corresponding bits of both operands are ones.
例如:
1111 & 0000
会 return 0000
1111 & 0001
会 return 0001
1111 & 0010
会 return 0010
1111 & 0100
会 return 0100
但是,正如您在文档中看到的那样:
Bitwise operators perform their operations on such binary representations, but they return standard JavaScript numerical values.
如果您对整数使用此运算符,您将得到整数而不是二进制。
在您的情况下,使用 number & 255
可确保最终值在 0 到 255 的范围内。
您可以阅读有关按位运算符的更多信息 there。
所以我在 codewars.com 遇到了一些问题,我遇到了一个关于基本加密的问题 (https://www.codewars.com/kata/basic-encryption/javascript)。目标是获取一个字符串值并将其在 ASCII 图表上向右移动 x 个值。
这是我最初的解决方案:
function encrypt(text, rule) {
let res = ''
for(let i = 0; i<text.length; i++) {
res += (String.fromCharCode(text.charCodeAt(i)+rule))
}
return res
};
但是,它没有通过所有测试,所以我查看了解决方案,这就是让我通过测试的原因:
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
,有人可以向我解释添加它使我的代码有效后真正改变了什么吗?
正如上面有人所说,您的有效字符范围是从 0 到 255。有很多方法可以使这个条件有效,但 bitwise and
看起来是最短的一个。
Bitwise AND returns a one in each bit position for which the corresponding bits of both operands are ones.
例如:
1111 & 0000
会 return 0000
1111 & 0001
会 return 0001
1111 & 0010
会 return 0010
1111 & 0100
会 return 0100
但是,正如您在文档中看到的那样:
Bitwise operators perform their operations on such binary representations, but they return standard JavaScript numerical values.
如果您对整数使用此运算符,您将得到整数而不是二进制。
在您的情况下,使用 number & 255
可确保最终值在 0 到 255 的范围内。
您可以阅读有关按位运算符的更多信息 there。