如何在C#中将uint转换为int?
给定:
uint n = 3;
int i = checked((int)n); //throws OverflowException if n > Int32.MaxValue
int i = unchecked((int)n); //converts the bits only
//i will be negative if n > Int32.MaxValue
int i = (int)n; //same behavior as unchecked
或者
int i = Convert.ToInt32(n); //same behavior as checked
根据Kenan E. K.提到的信息进行了更新。
uint
大于int.MaxValue
,则使用强制转换会得到负数结果,而使用Convert.ToInt32
会导致异常。 - LukeH假设你只想简单地从一种类型中提取32位并将它们不加修改地转移到另一种类型中:
uint asUint = unchecked((uint)myInt);
int asInt = unchecked((int)myUint);
目标类型将盲目选择32位并重新解释它们。
相反,如果你更关心保持十进制/数值在目标类型本身的范围内:
uint asUint = checked((uint)myInt);
int asInt = checked((int)myUint);
在这种情况下,如果出现以下情况,您将会收到溢出异常:
在我们的情况下,我们希望unchecked
方案保持32位不变,因此这里有一些示例:
int....: 0000000000 (00-00-00-00)
asUint.: 0000000000 (00-00-00-00)
------------------------------
int....: 0000000001 (01-00-00-00)
asUint.: 0000000001 (01-00-00-00)
------------------------------
int....: -0000000001 (FF-FF-FF-FF)
asUint.: 4294967295 (FF-FF-FF-FF)
------------------------------
int....: 2147483647 (FF-FF-FF-7F)
asUint.: 2147483647 (FF-FF-FF-7F)
------------------------------
int....: -2147483648 (00-00-00-80)
asUint.: 2147483648 (00-00-00-80)
uint...: 0000000000 (00-00-00-00)
asInt..: 0000000000 (00-00-00-00)
------------------------------
uint...: 0000000001 (01-00-00-00)
asInt..: 0000000001 (01-00-00-00)
------------------------------
uint...: 2147483647 (FF-FF-FF-7F)
asInt..: 2147483647 (FF-FF-FF-7F)
------------------------------
uint...: 4294967295 (FF-FF-FF-FF)
asInt..: -0000000001 (FF-FF-FF-FF)
------------------------------
int[] testInts = { 0, 1, -1, int.MaxValue, int.MinValue };
uint[] testUints = { uint.MinValue, 1, uint.MaxValue / 2, uint.MaxValue };
foreach (var Int in testInts)
{
uint asUint = unchecked((uint)Int);
Console.WriteLine("int....: {0:D10} ({1})", Int, BitConverter.ToString(BitConverter.GetBytes(Int)));
Console.WriteLine("asUint.: {0:D10} ({1})", asUint, BitConverter.ToString(BitConverter.GetBytes(asUint)));
Console.WriteLine(new string('-',30));
}
Console.WriteLine(new string('=', 30));
foreach (var Uint in testUints)
{
int asInt = unchecked((int)Uint);
Console.WriteLine("uint...: {0:D10} ({1})", Uint, BitConverter.ToString(BitConverter.GetBytes(Uint)));
Console.WriteLine("asInt..: {0:D10} ({1})", asInt, BitConverter.ToString(BitConverter.GetBytes(asInt)));
Console.WriteLine(new string('-', 30));
}
Convert.ToInt32()
接受uint
作为值。
uint i = 10;
int j = (int)i;
或者
int k = Convert.ToInt32(i)
我会建议使用tryParse,如果uint太大而无法转换为int,则它将返回“false”。
不要忘记,只要您的值大于0,uint可以比int更大。
int intNumber = (int)uintNumber;
根据您期望的值类型,您可能需要在进行转换之前检查uintNumber的大小。 int的最大值约为uint的0.5。
uint
转换为long
会更安全,因为long
可以包含所有的uint
值,而int
则不能(正如已经提到的)。 - Liam