Bit manipulation of JavaScript, integer, binary

Source: Internet
Author: User

  bit and (x&y): binary operation of the operand, if the two operand of a two is 1, the corresponding result bit is set to 1.

0x0007 & 0x0003 = 0x0003

\

A small old brown dog: 64 + 16 + 8 + 2 = 90

Search for a pet with a specific tag, only need to do bit and operation with the search value.

Search large young white pet var searchFlags = + + + 4;var pets = []; Pet var numpets = Pets.length;for (var i = 0; i < numpets; i++) {if (searchFlags & pets[i].flags = = SearchFlags) {}}

bit or (x|y): Binary or operation of the operand, if one of the two operands has one for 1, the corresponding result bit is set to 1.

0x0007 | 0x0003 = 0x0007

  bitwise XOR (X^Y): A binary XOR operation on the operand, if only one of the two operands is 1, the corresponding result bit is set to 1.

0x0001 ^ 0x0000 = 0x0001 0x0001 ^ 0x0001 = 0x0000

Toggle is converted between 0 and 1 (assuming that the start toggle equals 0 or 1) toggle ^= 1;toggle = toggle? 0:1;

bit non (~x): All bits are reversed (if the operand is a signed integer (the leftmost bit is the sign bit), the ~ operator equals minus 1).

11100111 Inversion is 00011000

  bit left shift (x<<numbits): numbits bits to the left of the binary of X. All bits are shifted to the left, the leftmost bits are lost, and 0 fills the right-most bit. Multiplication x* equivalent to unsigned integers (2^numbits)

y = 5 << 1; y=10; = = Math.floor (5* (2^1)) y = 5 << 2; y=20; = = Math.floor (5* (2^2)) y = 5 << 3; y=40; = Math.floor (5* (2^3))

arithmetic bit left shift (x>>numbits): numbits bits to the right of the binary of X. In addition to the leftmost sign bit, all bits move to the right and the right bit is lost. Division x/(2^numbits) equivalent to signed integers

y = 5 >> 1; y=5; = = Math.floor (5/(2^1)) y = 5 >> 2; y=2; = = Math.floor (5/(2^2)) y = 5 >> 3; Y=1; = = Math.floor (5/(2^3)) x = y >> 0; is a fast x = Math.floor (y)

Bit manipulation of JavaScript, integer, binary

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.