什么是用C无符号整型和有符号整数之间的差异? [英] What is a difference between unsigned int and signed int in C?

查看:260
本文介绍了什么是用C无符号整型和有符号整数之间的差异?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下定义:

int x=5;
int y=-5;
unsigned int z=5;

他们是如何存储在内存中?任何人都可以解释这些比特重presentation内存?

How are they stored in memory? Can anybody explain the bit representation of these in memory?

能否 INT X = 5 INT Y = -5 有重新在内存presentation相同的位?

Can int x=5 and int y=-5 have same bit representation in memory?

推荐答案

ISO C规定的差别是什么。

ISO C states what the differences are.

INT 数据类型是签名和通过具有包容32767至少-32767最小范围。实际值在 limits.h中给出 INT_MIN INT_MAX 分别。

The int data type is signed and has a minimum range of at least -32767 through 32767 inclusive. The actual values are given in limits.h as INT_MIN and INT_MAX respectively.

这是 unsigned int类型有65535包容与实际最高值为 UINT_MAX 从最小的范围为0相同的头文件。

An unsigned int has a minimal range of 0 through 65535 inclusive with the actual maximum value being UINT_MAX from that same header file.

除此之外,该标准并不强制二进制补码表示法编码值,这只是可能性之一。三个允许的类型将具有(使用16位数据类型)为5和-5以下的编码:

Beyond that, the standard does not mandate twos complement notation for encoding the values, that's just one of the possibilities. The three allowed types would have encodings of the following for 5 and -5 (using 16-bit data types):

        two's complement  |  ones' complement   |   sign/magnitude
    +---------------------+---------------------+---------------------+
 5  | 0000 0000 0000 0101 | 0000 0000 0000 0101 | 0000 0000 0000 0101 |
-5  | 1111 1111 1111 1011 | 1111 1111 1111 1010 | 1000 0000 0000 0101 |
    +---------------------+---------------------+---------------------+


  • 在二的补码,则通过反转所有位然后加入1得到一个负的若干

  • 在一补数,你颠倒所有位得到一个负一些。

  • 在符号/幅度,最高位是符号,所以你只是倒置,要得到否定的。

  • 注意,正值有相同编码的所有重新presentations,只有负值是不同的。

    Note that positive values have the same encoding for all representations, only the negative values are different.

    请注意进一步指出,对于无符号数,你并不需要使用一个标志位之一。这意味着你会得到积极的一面更多范围(无负编码的成本,当然)。

    Note further that, for unsigned values, you do not need to use one of the bits for a sign. That means you get more range on the positive side (at the cost of no negative encodings, of course).

    和没有, 5 -5 不能有相同的编码,无论哪个重新presentation你使用。否则,会是没有办法分辨出来。

    And no, 5 and -5 cannot have the same encoding regardless of which representation you use. Otherwise, there'd be no way to tell the difference.

    这篇关于什么是用C无符号整型和有符号整数之间的差异?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆