int to unsigned int conversion

前端 未结 6 1528
长发绾君心
长发绾君心 2020-11-29 20:33

I\'m just amazed to know that I can\'t convert signed to unsigned int by casting!

int i = -62;
unsigned int j = (unsigned int)i;

I thought

相关标签:
6条回答
  • 2020-11-29 20:56

    with a little help of math

    #include <math.h>
    int main(){
      int a = -1;
      unsigned int b;
      b = abs(a);
    }
    
    0 讨论(0)
  • 2020-11-29 21:01

    i=-62 . If you want to convert it to a unsigned representation. It would be 4294967234 for a 32 bit integer. A simple way would be to

    num=-62
    unsigned int n;
    n = num
    cout<<n;
    

    4294967234

    0 讨论(0)
  • 2020-11-29 21:06

    You can convert an int to an unsigned int. The conversion is valid and well-defined.

    Since the value is negative, UINT_MAX + 1 is added to it so that the value is a valid unsigned quantity. (Technically, 2N is added to it, where N is the number of bits used to represent the unsigned type.)

    In this case, since int on your platform has a width of 32 bits, 62 is subtracted from 232, yielding 4,294,967,234.

    0 讨论(0)
  • 2020-11-29 21:06

    Edit: As has been noted in the other answers, the standard actually guarantees that "the resulting value is the least unsigned integer congruent to the source integer (modulo 2n where n is the number of bits used to represent the unsigned type)". So even if your platform did not store signed ints as two's complement, the behavior would be the same.


    Apparently your signed integer -62 is stored in two's complement (Wikipedia) on your platform:

    62 as a 32-bit integer written in binary is

    0000 0000 0000 0000 0000 0000 0011 1110
    

    To compute the two's complement (for storing -62), first invert all the bits

    1111 1111 1111 1111 1111 1111 1100 0001
    

    then add one

    1111 1111 1111 1111 1111 1111 1100 0010
    

    And if you interpret this as an unsigned 32-bit integer (as your computer will do if you cast it), you'll end up with 4294967234 :-)

    0 讨论(0)
  • 2020-11-29 21:11

    This conversion is well defined and will yield the value UINT_MAX - 61. On a platform where unsigned int is a 32-bit type (most common platforms, these days), this is precisely the value that others are reporting. Other values are possible, however.

    The actual language in the standard is

    If the destination type is unsigned, the resulting value is the least unsigned integer congruent to the source integer (modulo 2^n where n is the number of bits used to represent the unsigned type).

    0 讨论(0)
  • 2020-11-29 21:13

    Since we know that i is an int, you can just go ahead and unsigneding it!

    This would do the trick:

    int i = -62;
    unsigned int j = unsigned(i);
    
    0 讨论(0)
提交回复
热议问题