宽度不兼容的变量
我使用以下代码来简化将大值分配给内存中的特定位置:
int buffer_address = virtual_to_physical(malloc(BUFFER_SIZE));
unsigned long int ring_slot = buffer_address << 32 | BUFFER_SIZE;
但是,编译器抱怨“警告:左移计数>=类型宽度”。但是 C 中的 unsigned long int 是 64 位,因此将 int (32 位)向左移动 32 位应该会产生 64 位值,因此编译器不应该抱怨。但确实如此。
我是否遗漏了一些明显的东西,或者是否有一个简单的解决方法?
I am using the following code to simplify assigning large values to specific locations in memory:
int buffer_address = virtual_to_physical(malloc(BUFFER_SIZE));
unsigned long int ring_slot = buffer_address << 32 | BUFFER_SIZE;
However, the compiler complains "warning: left shift count >= width of type". But an unsigned long int in C is 64 bits, so bit-shifting an int (32 bits) to the left 32 bits should yield a 64 bit value, and hence the compiler shouldn't complain. But it does.
Is there something obvious I'm missing, or otherwise is there a simple workaround?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
unsigned long int
不一定是 64 位,但为了简单起见,我们假设它是 64 位。buffer_address
的类型为int
。buffer_address
上没有任何“更高”类型的任何表达式都应返回 int。从而buffer_address << 32 应该返回 int,而不是unsigned long
。因此编译器会抱怨。不过,这应该可以解决您的问题:
请注意,
unsigned long
不一定一定是 64 位,这取决于实现。使用这个代替:An
unsigned long int
is not necessarily 64 bits, but for the simplicity let's assume it is.buffer_address
is of typeint
. Any expression without any "higher" types onbuffer_address
should return int. Therebybuffer_address << 32
should return int, and notunsigned long
. Thus the compiler complains.This should solve your issue though:
Please note, an
unsigned long
is not necessarily 64 bits, this depends on the implementation. Use this instead:buffer_address
是一个(32 位)int
,因此buffer_size << 32
正在将其移动大于或等于其大小的量。请注意,“unsigned long”不必是 64 位(它不在 Windows 上 - 32 位 (ILP32) 或 64 位 (LLP64);也不在 32 位 Unix 机器 (ILP32) 上)。要获得有保证的(至少)64 位整数,您需要
unsigned long long
。很少有机器的
int
是 64 位数量 (ILP64); DEC Alpha 就是其中之一,我相信一些 Cray 机器也使用了它(并且 Cray 也使用“大”char
类型 - 每个char
超过 8 位)。buffer_address
is a (32-bit)int
, sobuffer_size << 32
is shifting it by an amount greater than or equal to its size.Note that 'unsigned long' need not be 64-bits (it is not on Windows - 32-bit (ILP32) or 64-bit (LLP64); nor it is on a 32-bit Unix machine (ILP32)). To get a guaranteed (at least) 64-bit integer, you need
unsigned long long
.There are few machines where
int
is a 64-bit quantity (ILP64); the DEC Alpha was one such, and I believe some Cray machines also used that (and the Cray's also used 'big'char
types - more than 8 bits perchar
).=
符号右侧表达式的结果不取决于它被分配的内容。您必须首先强制转换为 unsigned long。The result of the expression on the right side of the
=
sign does not depend on what it's assigned to. You must cast to unsigned long first.