Home > Web Front-end > JS Tutorial > Usage examples of bitwise operators in js (code)

Usage examples of bitwise operators in js (code)

不言
Release: 2018-08-17 17:11:52
Original
1709 people have browsed it

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
};
Copy after login

Related recommendations:

JavaScript bit operators

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template