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.
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
There are few ways to convert int
to uint
int x;
Technique #1
uint y = Convert.ToUInt32(x);
Technique #2
uint y = checked((uint) x);
Technique #3
uint y = unchecked((uint) x);
Technique #4
uint y = (uint) x;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With