我不明白为什么C#将字面值0xFFFFFFFF视为uint,当它对int类型也表示为-1时。
以下是代码输入到此处显示的立即窗口中,输出:
int i = -1;
-1
string s = i.ToString("x");
“FFFFFFFF”
int j = Convert.ToInt32(s, 16);
-1
int k = 0xFFFFFFFF;
无法将类型'uint'隐式转换为'int'。存在显式转换(您是否错过了演员?)
int l = Convert.ToInt32(0xFFFFFFFF);
OverflowException未处理:对于Int32,值太大或太小。
为什么字符串十六进制数字可以毫无问题地转换,但文字只能使用未选中转换?
答案 0 :(得分:7)
Why is 0xFFFFFFFF a uint when it represents -1?
Because you're not writing the bit pattern when you write
i = 0xFFFFFFFF;
you're writing a number by C#'s rules for integer literals. With C#'s integer literals, to write a negative number we write a -
followed by the magnitude of the number (e.g., -1
), not the bit pattern for what we want. It's really good that we aren't expected to write the bit pattern, it would make it really awkward to write negative numbers. When I want -3, I don't want to have to write 0xFFFFFFFD
. :-) And I really don't want to have to vary the number of leading F
s based on the size of the type (0xFFFFFFFFFFFFFFFD
for a long
-3
).
The rule for choosing the type of the literal is covered by the above link by saying:
If the literal has no suffix, it has the first of these types in which its value can be represented:
int
,uint
,long
,ulong
.
0xFFFFFFFF
doesn't fit in an int
, which has a maximum positive value of 0x7FFFFFFF
, so the next in the list is uint
, which it does fit in.
答案 1 :(得分:4)
0xffffffff
is 4294967295
is an UInt32 that just happens to have a bit pattern equal to the Int32 -1
due to the way negative numbers are represented on computers. Just because they have the same bit pattern, that doesn't mean 4294967295 = -1. They're completely different numbers so of course you can't just trivially convert between the two. You can force the reintepretation of the bit pattern by using an explicit cast to int: (int)0xffffffff
.
答案 2 :(得分:0)
The C# language rules state that 0xFFFFFFFF is an unsigned
literal.
A C# signed int
is 2's complement type. That scheme uses 0xFFFFFFFF to represent -1. (2's complement is a clever scheme since it doesn't have a signed zero).
For an unsigned int, 0xFFFFFFFF is the largest value it can take, and due to its size, it can't be converted to a signed int
.
答案 3 :(得分:0)
The C# docs say that the compiler will try to fit the number you provide in the smallest type that can fit it. That doc is a bit old, but it applies still. It always assumes that the number is positive.
As a fallback you can always coerce the type.