Bitwise anti-operator in Javascript (~) _ Basic knowledge

Source: Internet
Author: User
Bitwise anti-operator (~) in Javascript (~), Executes bitwise non (evaluate not) operations on an expression. For example ~ 1-2 ;~ 2-3 ;~ 99-100 The Code is as follows:


Result = ~ [Number]

All unary operators (such ~ Operators) are calculated according to the following rules:

The Code is as follows:


1. If it is applied to an undefined or null expression, a runtime error is thrown.
2. convert an object to a string.
3. If possible, convert the string to a number. Otherwise, a running error occurs.
4. the Boolean value is regarded as a number (if it is false, it is 0; if it is true, it is 1 ).

The operator is applied to the result number.

~ Operator to view the value in the binary representation of the expression and perform a bit non-operation.

If any one of the bits in the expression is 1, the bit in the result is 0. If any one of the bits in the expression is 0, the bit in the result is changed to 1.

The following example illustrates the bitwise (~) The usage of the operator, which contains binary numbers that represent negative decimal numbers. If you are not familiar with this operation, please first read "convert a decimal number to binary, octal, and hexadecimal".

The Code is as follows:


Var temp = ~ 5;
/*
5 binary 101, full 32 bits
00000000000000000000000000000101
Bitwise Inversion
11111111111111111111111111111010
Because the first one starting with 32 bits is 1, this is a negative number. to convert the binary into a negative number, we need to reverse code it first.
00000000000000000000000000000101
Then, + 1
00000000000000000000000000000110
Convert to 6 in decimal format, and add the symbol to negative number-6.
*/
Alert (temp );
// Pop up [-6]

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.