6

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
  • 111
  • 1
  • 1
  • 2

5 Answers5

10

Use

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

Or even better

uint num10 = (uint.MaxValue) >> (0x20u - num9);
p.s.w.g
  • 136,020
  • 27
  • 262
  • 299
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
  • 19,061
  • 9
  • 47
  • 81
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
  • 56,954
  • 26
  • 136
  • 173
1

Look up the unchecked context.

uncleO
  • 7,997
  • 2
  • 20
  • 37
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
  • 26
  • 1
  • 1