How can I convert a signed integer into an unsigned integer?

codemilan picture codemilan · Mar 2, 2017 · Viewed 17.3k times · Source

The piece of code is like:-

int x = -24;  
uint y = (uint) x;  
Console.WriteLine("*****" + y + "********");  
// o/p is *****4294967272********  

Why this type of behavior in C#, Detailed elaboration would be helpful. Thankyou all.

Answer

Dmitry Bychenko picture Dmitry Bychenko · Mar 2, 2017

Negative numbers (like -24) are represented as a binary complement, see

en.wikipedia.org/wiki/Two's_complement

for details. In your case

   24     = 00000000000000000000000000011000
  ~24     = 11111111111111111111111111100111
  ~24 + 1 = 11111111111111111111111111101000 =
          = 4294967272

When casting int to uint be careful, since -24 is beyond uint range (which [0..uint.MaxValue]) you can have OverflowException being thrown. A safier implementation is

 int x = -24;  
 uint y = unchecked((uint) x); // do not throw OverflowException exception