What happens when I assign long int to int in C?

后端 未结 2 1436
旧巷少年郎
旧巷少年郎 2020-12-02 21:59

In a recent homework assignment I\'ve been told to use long variable to store a result, since it may be a big number.

I decided to check will it really

2条回答
  •  没有蜡笔的小新
    2020-12-02 22:37

    A long can always represent all values of int. If the value at hand can be represented by the type of the variable you assign to, then the value is preserved.

    If it can't be represented, then for signed destination type the result is formally unspecified, while for unsigned destination type it is specified as the original value modulo 2n, where n is the number of bits in the value representation (which is not necessarily all the bits in the destination).

    In practice, on modern machines you get wrapping also for signed types.

    That's because modern machines use two's complement form to represent signed integers, without any bits used to denote "invalid value" or such – i.e., all bits used for value representation.

    With n bits value representation any integer value is x is mapped to x+K*2n with the integer constant K chosen such that the result is in the range where half of the possible values are negative.

    Thus, for example, with 32-bit int the value -7 is represented as bitpattern number -7+232 = 232-7, so that if you display the number that the bitpattern stands for as unsigned integer, you get a pretty large number.

    The reason that this is called two's complement is because it makes sense for the binary numeral system, the base two numeral system. For the binary numeral system there's also a ones' (note the placement of the apostrophe) complement. Similarly, for the decimal numberal system there's ten's complement and niners' complement. With 4 digit ten's complement representation you would represent -7 as 10000-7 = 9993. That's all, really.

提交回复
热议问题