C/C++中类型变量转换之间的数值溢出

版权声明:转载请注明文章出处,否则不得转载! https://blog.csdn.net/hanxiaoyong_/article/details/88774694

在编程中,不同类型的值转换时会产生溢出问题,溢出问题的主要发生在类型范围大的数值转换成范围小的数值的过程中。

例:double->float->long->int->short->byte/char。

下面举个例子:

#include <stdlib.h>
#include <stdio.h>
void main()
{
    int m_a = 200;
    byte m_b = ( byte)m_a; 
    printf("%d",m_b);

}

其中:

32位int

          0000 0000 0000 0000 0000 0000 1100 1000

 8位的char               

                                                                1100 1000

数在计算机中以补码形式存放在内存中,通过求原码来计算真值。

补码-1 =反码,反码取反得原码,原码: 1011 1000

所以输出的为-56。

关于原码,补码的知识,可以参考我的其他博文。

猜你喜欢

转载自blog.csdn.net/hanxiaoyong_/article/details/88774694