简体   繁体   English

在C#中将类型'uint'转换为'int'

[英]convert type 'uint' to 'int' in C#

I am trying to assign an int to an hex number. 我正在尝试将一个int分配给一个十六进制数字。 const int a = 0xFFFFFFF0; const int a = 0xFFFFFFF0; I got an error: Cannot implicitly convert type 'uint'. 我收到一个错误:无法隐式转换类型'uint'。 An explicit conversion exsist (are you missing a cast?) Does someone know how to fix it? 存在明确的转换(您是否缺少演员表?)有人知道如何解决此问题吗? tnx n

    const int a = unchecked((int)0xFFFFFFF0);

或更简单:

    const int a = -16;

use 使用

const uint a = 0xFFFFFFF0

;-) ;-)

Background: 0xFFFFFFF0 is too big to fit into an int , which goes from − 2,147,483,648 to 2,147,483,647, where as uint goes from 0 to 4,294,967,295, which is just above 0xFFFFFFF0 (= 4,294,967,280). 背景: 0xFFFFFFF0太大而无法容纳一个int ,它的值从− 2,147,483,648到2,147,483,647,而uint从0到4,294,967,295,这刚好大于0xFFFFFFF0 (= 4,294,967,280)。

Int32.MaxValue is 0x7FFFFFFF . Int32.MaxValue是0x7FFFFFFF。 I guess c# is trying to convert the value you're trying to assing to a uint (which can accomodate it) before assigning it 我想C#尝试在分配值之前将您要尝试赋值的值转换为uint(可以容纳它)

there is another way to convert without using the unchecked keyword: 还有另一种不使用unchecked关键字进行转换的方法:

uint ui = 0xFFFFFFFF;

int ii = System.BitConverter.ToInt32(BitConverter.GetBytes(ui),0);// this is -1

将0xFFFFFFF0变量存储到uint中,因为它太大而无法容纳在int中

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

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