码迷,mamicode.com
首页 > 其他好文 > 详细

02_有符号数与无符号数

时间:2018-10-23 21:01:05      阅读:133      评论:0      收藏:0      [点我收藏+]

标签:ott   range   编程   分享图片   include   lin   原码   固定   无符号   

有符号数与无符号数

1、计算机中的符号位

技术分享图片
编程实验:

#include <stdio.h>

int main()
{
    char c = -5;
    short s = 6;
    int i = -7;

    printf("%d\n", ( (c & 0x80) != 0 ));
    printf("%d\n", ( (s & 0x8000) != 0 ));
    printf("%d\n", ( (i & 0x80000000) != 0 ));

    return 0;
}

输出结果为:
技术分享图片

2、有符号数的表示方法

在计算机内部用补码表示有符号数
正数的补码为正数本身
负数的补码为负数的绝对值各位取反后加1
8位整数5的补码 0000 0101
8位整数-7的补码 1111 1001
16位整数20的补码 0000 0000 0001 0100
16位整数-13的补码 1111 1111 1111 0011

3、无符号数的表示方法

在计算机内部用原码表示无符号数
- 无符号数默认为正数
- 无符号数没有符号位

对于固定长度的无符号数
- MAX_VALUE + 1 → MIN_VALUE
- MIN_VALUE - 1 → MAX_VALUE
举例:
一个字节大小的无符号数 1111 1111 + 1 = 0
一个字节大小的无符号数 0 - 1 = 1111 1111

4、当有符号数遇上无符号数

当无符号数与有符号数混合计算时,会将有符号数转化为无符号数后再进行计算,结果为无符号数。
编程实验:

#include <stdio.h>

int main()
{
    unsigned int i = 5;
    int j = -10;

    if( (i + j) > 0 )
    {
        printf("i + j > 0\n");
    }
    else
    {
        printf("i + j <= 0\n");
    }

 if(i > j)
  printf("i > j\n");
 else if(i < j)
  printf("i < j\n");

 return 0;
}

输出结果为:
技术分享图片

5、错误地使用unsigned

编程实验:

#include <stdio.h>

int main()
{
    unsigned int i = 0;

    for(i=9; i>=0; i--)
    {
        printf("i = %u\n", i);
    }

    return 0;
}

输出结果为:死循环
原因:变量i是unsigned int类型,一直都是大于等于0的,所以for循环的条件一直都成立

6、小结

技术分享图片

<wiz_tmp_tag id="wiz-table-range-border" contenteditable="false" style="display: none;">





02_有符号数与无符号数

标签:ott   range   编程   分享图片   include   lin   原码   固定   无符号   

原文地址:https://www.cnblogs.com/chen-ace/p/9838182.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!