Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert -1 to uint C#

Converting -1 to uint will not work "((uint)(-1))" solution?

num10 = ((uint)(-1)) >> (0x20 - num9);

Error: Constant value '-1' cannot be converted to a 'uint' (use 'unchecked' syntax to override)

like image 945
user2089096 Avatar asked Mar 17 '13 06:03

user2089096


People also ask

How do I convert to unsigned?

To convert a signed integer to an unsigned integer, or to convert an unsigned integer to a signed integer you need only use a cast. For example: int a = 6; unsigned int b; int c; b = (unsigned int)a; c = (int)b; Actually in many cases you can dispense with the cast.

Can I cast int to Uint?

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.)

What is Uint in C?

uint is a keyword that is used to declare a variable which can store an integral type of value (unsigned integer) from the range of 0 to 4,294,967,295. It keyword is an alias of System. UInt32. uint keyword occupies 4 bytes (32 bits) space in the memory.

Is unsigned int same as Uint?

Unsigned Integers (often called "uints") are just like integers (whole numbers) but have the property that they don't have a + or - sign associated with them. Thus they are always non-negative (zero or positive).


4 Answers

Use

uint minus1 = unchecked((uint)-1);
uint num10 = (minus1) >> (0x20 - num9);

Or even better

uint num10 = (uint.MaxValue) >> (0x20u - num9);
like image 63
p.s.w.g Avatar answered Oct 23 '22 04:10

p.s.w.g


The compiler is telling you what you need to do:

unchecked
{
     num10 = ((uint)(-1)) >> (0x20 - num9);
}

However, it may not give you the result you want.

like image 36
Inisheer Avatar answered Oct 23 '22 03:10

Inisheer


An unsigned integer can represent positive values only. It can't represent -1.

If you want to represent negative values, you'll need to use a signed type, like int.

like image 34
Michael Petrotta Avatar answered Oct 23 '22 04:10

Michael Petrotta


Look up the unchecked context.

like image 1
uncleO Avatar answered Oct 23 '22 04:10

uncleO