0

I don't understand how the type conversion works on below initialization "unsigned int i = -100;".

My understanding is that -100 is explicitly converted from signed integer to unsigned integer.

signed integer: -100(10) = 10011100(2)

↓↓↓

unsigned integer: ?

Below is the code and output. I got "4294967196" as unsigned int. Why is this number that big? How this type cast works? Thank you for helping me out!

// unsigned int, if 8 bit, range 0 to 255 
unsigned int i = -100;
cout << "i = " << i << endl;  // I get i = 4294967196
cout << "i(unsigned int) = " << (unsigned int)i << endl; // I get i(unsigned int) = 4294967196
cout << "i(int) = " << (int)i << endl; // I get i(int) = -100

My test environment:

OS: Windows 10 Pro (64 bit)
IDE: Visual Studio Community 2019
  • 2
    The rule is that the value is adjusted modulo (UINT_MAX+1). So you will get 2^32 - 100 if your system is normal and has 32-bit int – M.M Sep 19 '21 at 22:45
  • 1
    You wrote down 8 bits to represent the value. Not enough, integral literals are of type int, so write 32 of them and it will be obvious. – Hans Passant Sep 19 '21 at 22:54
  • @M.M Thank you for your comment! I reviewed some references as below. I still don't understand why it will be subtraction like 2^32 - 100. [Limits on Integer Constants](https://learn.microsoft.com/en-us/cpp/cpp/integer-limits?view=msvc-160) UINT_MAX = Maximum value for a variable of type unsigned int = 4294967295 (0xffffffff) 32 bit unsigned int range : 0 to 4,294,967,295 (2^32 = 4,294,967,296) – yurachika2020 Sep 19 '21 at 22:57
  • 1
    Look up "modular arithmetic" in mod N, -100 is the same number as N-100 . – M.M Sep 19 '21 at 23:06
  • 2
    `-100` is commonly represented as `11111111111111111111111110011100` in binary, **not** `10011100`. This assumes your `int` is 32 bits. – Drew Dormann Sep 19 '21 at 23:07
  • 2
    Does this answer your question? [What happens if I assign a negative value to an unsigned variable?](https://stackoverflow.com/questions/2711522/what-happens-if-i-assign-a-negative-value-to-an-unsigned-variable) – Nate Eldredge Sep 19 '21 at 23:51
  • 3
    voted to reopen -- the question is clearly about programming but it should be closed as duplicate, not as "question is not about programing" – M.M Sep 20 '21 at 00:04
  • @M.M Thank you for your suggestion! I am not familiar with "modular arithmetic" so I will look into it. I appreciate it. :) – yurachika2020 Sep 20 '21 at 01:03
  • @DrewDormann Thank you for your detailed and clear explanation. I understood. Thank you for your help! – yurachika2020 Sep 20 '21 at 01:03
  • @NateEldredge Yes, I read the answers to the question. Thank you so much! – yurachika2020 Sep 20 '21 at 04:33

0 Answers0