char c language type of spill

Recent study data structures using c language to write a code expression evaluation, using the char type, an error has occurred, and finally found a char overflow problem, I would have to complement the original code anti code stored in the computer's calculation less likely, I think about it a long time actually cured my insomnia, have to admit that I really do not fit to be a programmer, this technique I live this woman can not do it, did not talk much, and share with you my little harvest, little Joseph about.

Converting the complex problem into a simple user-friendly program to explain to you


#include<stdio.h>
int main()
{
    char c=168;
    printf("%d",c-48);
    return 0;
}

-136
Process returned 0 (0x0)   execution time : 0.196 s
Press any key to continue.


analyse as below:

char type c only one byte language, default char is signed char, in the range from -128 to 127

168 char is defined, then, cross-border, and will be treated as follows

168 is a positive number, the original code is 10101000, and the computer is stored in accordance with the calculated complement form, complement positive number equal to the original code, there is the computer 10101000

Computer when read, the most significant bit is treated as the sign bit, because the most significant bit is 1, it is negative, and because computing storage complement form, find the original value of the original order code

Original code equals negative complement complement, the sign bit is unchanged, the other bit inversion plus a last one, 11011000, is converted into a most significant bit - number, the result is -88

When the output is c-48, so the result is -88-48 = -136


#include<stdio.h>
int main()
{
    char c=128;
    printf("%d",c);
    return 0;
}

-128
Process returned 0 (0x0)   execution time : 1.562 s
Press any key to continue.


analyse as below:

Then -128, which is an original code (sign bit) 10000000, the sign bit constant plus a rear end of the other bits negated, as obtained by 1's complement (sign bit) 10000000, since a byte char type, only memory 8, the memory 10000000

Reading, since the first one is, negative, so the other bits plus a bitwise negation, the result of 10 million, 128, so -128

128 is a positive number, equal to the complement of the original code 10000000, stored in the computer, because it is equal to the complement -128, -128 the output

to sum up:

1. The number of the original is converted into a binary, two's complement obtaining, taken overflow bits matching, stored in the computer

2. When reading, the highest bit is a sign bit, and then according to the corresponding symbols values ​​of the corresponding process, reading data

Published 34 original articles · won praise 38 · views 2652

Guess you like

Origin blog.csdn.net/qq_43779149/article/details/104194698