无法将 32 位十六进制值分配给整数

Can't assign 32bit hexadecimal value to integer

First, this question has related posts: Why Int32 maximum value is 0x7FFFFFFF?

但是,我想知道为什么十六进制值总是被视为无符号数。

请参阅以下代码段:

byte  a = 0xFF;               //No error (byte is an unsigned type).
short b = 0xFFFF;             //Error! (even though both types are 16 bits).
int   c = 0xFFFFFFFF;         //Error! (even though both types are 32 bits).
long  d = 0xFFFFFFFFFFFFFFFF; //Error! (even though both types are 64 bits).

错误的原因是十六进制值始终被视为无符号值,无论它们存储为何种数据类型。因此,对于所描述的数据类型,该值为 'too large'


例如,我预计:

int c = 0xFFFFFFFF;

存储值:

-1

而不是值:

4294967295

仅仅是因为intsigned类型。


那么,为什么十六进制值总是被视为无符号,即使符号类型可以由用于存储它们的数据类型推断出来?

如何在不使用 ushortuintulong 的情况下将这些位存储到这些数据类型中?

特别是,考虑到我不能使用更大的签名数据类型,我如何才能为 long 数据类型实现这一点?

发生的事情是字面量本质上是类型化的。 0.1double,这就是为什么你不能说 float f = 0.1。您可以将 cast a double 转换为 float (float f = (float)0.1),但您可能会失去精度。同样,文字 0xFFFFFFFF 本质上是 uint。您可以将它转换为 int,但在 之后它已被编译器解释为 uint。编译器不会使用您分配给它的变量来确定其类型;它的类型由它的文字类型定义。

它们被视为无符号数,即 what the language specification says to do