Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

integer

uint

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.

like image 774
codemilan Avatar asked Mar 02 '17 06:03

codemilan


2 Answers

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  
like image 90
Dmitry Bychenko Avatar answered Oct 14 '22 17:10

Dmitry Bychenko


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;
like image 37
Sachith Wickramaarachchi Avatar answered Oct 14 '22 16:10

Sachith Wickramaarachchi