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)
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)
Use
uint minus1 = unchecked((uint)-1);
uint num10 = (minus1) >> (0x20 - num9);
Or even better
uint num10 = (uint.MaxValue) >> (0x20u - num9);
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.
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
.
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