简体   繁体   English

将-1转换为uint C#

[英]Convert -1 to uint C#

Converting -1 to uint will not work "((uint)(-1))" solution? 将-1转换为uint将不起作用“((uint)( - 1))”解决方案?

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

Error: Constant value '-1' cannot be converted to a 'uint' (use 'unchecked' syntax to override) 错误:常量值'-1'无法转换为'uint'(使用'unchecked'语法覆盖)

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. 它不能代表-1。

If you want to represent negative values, you'll need to use a signed type, like int . 如果要表示负值,则需要使用带符号的类型,如int

查找未选中的上下文。

You can indeed have something that resembles negative, unsigned numbers somewhat. 你确实可以在某种程度上拥有类似于负数,无符号数的东西。 They have the feature that x + (-x) == 0 它们具有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 要在没有未选中区域的情况下在c#中创建“否定”uint,可以使用与-x相同的等效(~x) + 1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM