C + + int negative complement implicit type conversion

Source: Internet
Author: User

    1 ;     int x =-2;     << x + y << Endl;

For the above results the

There's a minus-complement problem and implicit type conversion between different types.

First, the representation of negative numbers is the absolute value of the negative number of binary code inversion plus 1,-2 complement calculation is:

0000 0000 0000 0010->1111 1111 1111 1101->1111 1111 1111 1111 1110

and the addition and subtraction of integers are implemented by adding operations, the main reason is that the use of complement, can be the symbol bit and other bits unified processing, at the same time, subtraction can also be processed by addition. In addition, if the highest bit (sign bit) has a carry, the carry is discarded when the number of two complements is added.

The binary representation of 1 is: 0000 0000 0000 0001

The binary representation of X + Y in the interior is 1111 1111 1111 1111

There is an implicit type conversion rule for the last type, and the two general guidelines are as follows:
1, in order to prevent the loss of precision, if necessary, the type is always promoted to a wider type.
2. All arithmetic expressions that contain an ordered type smaller than the shape will be converted to shaping before the calculation.

In general, the conversion order for various types is long double > double > float >= int >= short > char,unsigned > signed.

As a result of unsigned > signed, x+y is interpreted as unsigned, and the last output value is 2 of 32 square minus one

int value Range

-2^31 ~ 2^31-1

Why are negative numbers -2^31 instead of -2^31-1?

Because of the provisions of 1000 0000, 0000 0000, 0000 0000, 0000 0000 This special number (originally 0) for -2^31, so the negative number is one more

Similarly, the value range for char types is 128 to 127, which is also represented by 1000 0000 AS-128

C + + int negative complement implicit type conversion

Related Article

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.