2. Signed and unsigned numbers

Symbol bit in computer

1. The highest bit of the data type is used to identify the symbol of the data

  The highest digit is 1, indicating that this number is negative

 The highest bit is 0, indicating that this number is positive

2. Use a complement to indicate a signed number inside the computer

The complement of the positive number is the positive number itself

The complement of the negative number is the absolute value of the negative number

3. Use the original code to represent unsigned numbers inside the computer

Unsigned numbers default to positive numbers

Unsigned number without sign bit

4. For unsigned numbers of fixed length

MAX_VALUE + 1 -> MIN_VALUE

MIN_VALUE - 1->MAX_VALUE

5.signed 和unsigned 

Variables in C language default to signed types

The unsigned keyword declares that the variable is of unsigned type

The unsigned keyword can only modify variables of integer type

 

Example one

#include <QCoreApplication>
 
int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
 
    unsigned int i  = 6;
    int j = -12;
 
    if ( (i+j) > 0)
    {
        printf(" i + j > 0\n");
    }
    else
    {
        printf(" i + j < 0\n");
    }
    return a.exec();
}
What is the output of the program?

The result is i + j> 0 Cause: When unsigned and signed numbers are mixed, the signed number is converted to an unsigned number and then the calculation is performed. The result is an unsigned number.

 

Example two:

/*
 * Incorrect use of unsigned int as a loop variable
*/
void example2()
{
    unsigned int i = 0;
 
    for(i = 9 ; i >= 0; --i)
    {
        printf("i = %u\n",i);
    }
 
}
 
int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
 
    example2();
 
    return a.exec();
}
Output result: The printing continues all the time, because the minimum value of the unsigned number is 0. When 0 decreases by 1, it becomes a maximum number, which causes the cycle condition to be always satisfied.

 

Wow
Published 206 original articles · praised 18 · 70,000 views

Guess you like

Origin blog.csdn.net/lvmengzou/article/details/104221967