在 javascript 中,以下字符到字符二进制操作的测试打印 0
676 次:
var s = 'abcdefghijklmnopqrstuvwxyz';
var i, j;
for(i=0; i<s.length;i++){ for(j=0; j<s.length;j++){ console.log(s[i] | s[j]) }};
如果 js 使用字符串的实际二进制表示,我希望这里有一些非零值。
类似地,测试字符串和整数的二进制操作,下面分别打印 26 个 255
和 0
。 (选择 255 是因为它在二进制中是 11111111
)。
var s = 'abcdefghijklmnopqrstuvwxyz';
var i; for(i=0; i<s.length;i++){ console.log(s[i] | 255) }
var i; for(i=0; i<s.length;i++){ console.log(s[i] & 255) }
javascript 在这里做什么?似乎 javascript 在二进制操作之前将任何字符串转换为 false
。
注意事项
如果你在 python 中尝试这个,它会抛出一个错误:
>>> s = 'abcdefghijklmnopqrstuvwxyz'
>>> [c1 | c2 for c2 in s for c1 in s]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for |: 'str' and 'str'
但是像这样的东西似乎work in php .
最佳答案
在 JavaScript 中,当字符串与二元运算符一起使用时,它首先被转换为数字。下面显示了 ECMAScript 规范的相关部分,以解释其工作原理。
The production A : A @ B, where @ is one of the bitwise operators in the productions above, is evaluated as follows:
- Let lref be the result of evaluating A.
- Let lval be GetValue(lref).
- Let rref be the result of evaluating B.
- Let rval be GetValue(rref).
- Let lnum be ToInt32(lval).
- Let rnum be ToInt32(rval).
- Return the result of applying the bitwise operator @ to lnum and rnum. The result is a signed 32 bit integer.
ToInt32 :
The abstract operation ToInt32 converts its argument to one of 232 integer values in the range −231 through 231−1, inclusive. This abstract operation functions as follows:
- Let number be the result of calling ToNumber on the input argument.
- If number is NaN, +0, −0, +∞, or −∞, return +0.
- Let posInt be sign(number) * floor(abs(number)).
- Let int32bit be posInt modulo 232; that is, a finite integer value k of Number type with positive sign and less than 232 in magnitude such that the mathematical difference of posInt and k is mathematically an integer multiple of 232.
- If int32bit is greater than or equal to 231, return int32bit − 232, otherwise return int32bit.
对于任何不能解析为数字的字符串,内部 ToNumber 函数将返回 NaN,而 ToInt32(NaN) 将给出 0。因此在您的代码示例中,所有以字母作为操作数的按位运算符的计算结果为 0 | 0
,这解释了为什么只打印 0。
注意类似'7' | '8'
将评估为 7 | 8
因为在这种情况下用作操作数的字符串可以成功转换为数字。
至于为什么 Python 中的行为不同,Python 中实际上没有任何隐式类型转换,因此对于任何未实现二元运算符的类型(通过使用 __or__
、__and__
等),而字符串不实现这些二元运算符。
Perl 做了完全不同的事情,bitwise operators are implemented for strings它实际上会对每个字符串中的相应字节执行按位运算符。
如果您想使用 JavaScript 并获得与 Perl 相同的结果,您需要先使用 str.charCodeAt
将字符转换为其代码点。 ,对结果整数执行按位运算符,然后使用 String.fromCodePoint
将结果数值转换为字符。
关于javascript - javascript中字符串的按位运算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22212103/