This article brings you usage examples (code) of bitwise operators in js. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
MDN definition: Bitwise operators treat their operands as 32-bit binary strings (composed of 0s and 1s) rather than decimal octal or hexadecimal numbers.
For example: the decimal number 9 is represented as 1001 in binary. Bitwise operators perform operations on this binary representation, but the return result is a standard JavaScript value.
There are 7 bitwise operators, only one is discussed here: bitwise XOR^
Usage:
a^b, operation rules: in the bits of a and b In the representation, for each corresponding bit, if the two are not the same, 1 is returned, and if they are the same, 0 is returned.
Code example:
/** * @param {number[]} nums * @return {number} */ var singleNumber = function(nums) { // 如果相同数字,则其二进制都一样,返回0,不一样的返回1,这段代码,返回了nums数组中唯一不一样的值 var a for (var index=0, leng=nums.length; index<leng; index++){ a ^= nums[index] } return a };
Related recommendations:
Detailed introduction to bit operators and shift operations in Java
JS bitwise not (~) operator and ~~ operator understanding analysis_javascript skills
The above is the detailed content of Usage examples of bitwise operators in js (code). For more information, please follow other related articles on the PHP Chinese website!