0

我想将 a 初始化short为十六进制值,但我的编译器给了我截断警告。显然,它认为我正在尝试将 设置short为正值。

short my_value = 0xF00D; // Compiler sees "my_value = 61453"

你会如何避免这个警告?我可以只使用负值,

short my_value = -4083; // In 2's complement this is 0xF00D

但在我的代码中,使用十六进制更容易理解。

4

2 回答 2

3

Cast the constant.

short my_value = (short)0xF00D;

EDIT: Initial explanation made sense in my head, but on further reflection was kind of wrong. Still, this should suppress the warning and give you what you expect.

于 2010-11-18T20:23:21.070 回答
0

您正在分配一个不适合短的 int 值,因此会发出警告。您可以使用 c 类型强制转换使编译器静音,但这通常是一种不好的做法。

更好的方法是不这样做,并分配一个负值。或者,如果十六进制值更有意义,则切换到 unsigned short。

于 2010-11-18T21:03:28.183 回答