7

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)

user2089096
  • 121
  • 1
  • 1
  • 2

5 Answers5

12

Use

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

Or even better

uint num10 = (uint.MaxValue) >> (0x20u - num9);
p.s.w.g
  • 146,324
  • 30
  • 291
  • 331
2

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.

Inisheer
  • 20,376
  • 9
  • 50
  • 82
1

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.

Michael Petrotta
  • 59,888
  • 27
  • 145
  • 179
1

Look up the unchecked context.

UncleO
  • 8,299
  • 21
  • 29
1

You can indeed have something that resembles negative, unsigned numbers somewhat. They have the feature that x + (-x) == 0

To create a "negative" uint in c# without unchecked regions, you can instead use the equivalent (~x) + 1 which is the same as -x

kalleguld
  • 371
  • 3
  • 9