Unsigned and signed operations in the C language

Source: Internet
Author: User

With regard to the symbols in the computer, the representation of unsigned values and the operations between them are basic knowledge, but the work for so many years also dare not say fully understand thoroughly.

These days in the knowledge point has been some carding, and did some interesting experiments.


In a computer, the representation and operation of numeric values are expressed in complement. The complement of a positive number is its own, the complement of the negative is the highest sign bit is 1, the remaining bits take the inverse plus 1. For example, 5 is represented as 0xFFFB, and 5 is 0x0005.

Here, the first problem to be aware of is the operation between the signed number and the unsigned number. C language provisions, the first will be turned into an unsigned number, and then the operation.

For example, int iValue1 =-5;    unsigned int uValue2 = 2; The value of Ivalue1+uvalue2 is 0xFFFD, just like (unsigned int) iValue1 + uValue2


Another thing that means is that the division between the signed values is not equivalent to the right shift. For example-5/4 is not equal to -5>>2 the former result is 0xFFFF and then 0xFFFE

First, the former, for the division of the signed number, it is the actual equation ( -5+4-1) >>2 = (0xfffb+0x03) >>2=0xffff signed arithmetic right shift, the empty high position is replaced with the MSB sign;

In the latter case, -5>>2 is a straightforward arithmetic right shift, converted to 0xfffb>>2=0xFFFE


The last point to emphasize is that the division and right shift for unsigned numbers are equivalent, such as 5/4 = 5>>2

Unsigned and signed operations in the C language

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.