【问题标题】:left shift count >= width of type左移计数 >= 类型宽度
【发布时间】:2014-06-22 13:35:50
【问题描述】:

我知道以前在堆栈溢出时已经问过这个问题,但我已经尝试了所有建议的解决方案,但没有任何效果。我的问题很简单,我正在尝试定义一个无符号长整数,它必须采用允许的最大可能值。

#define SIZEOF_ULONG (sizeof(long) * 8);
#define LARGEST_VALUE (1ULL << ((SIZEOF_ULONG)-1));

其中 ulong 的类型定义为 unsigned long。我收到一个警告,左移计数 >= 类型宽度。我在我的 64 位机器上检查了 unsigned long 的大小,它是 8B。最后,我尝试使用 -m64 标志进行编译,但都是徒劳的。

有什么想法吗?

【问题讨论】:

  • 它应该是sizeof(unsigned long)*CHAR_BIT 以获得更多可移植性

标签: c++ c g++ bit-shift


【解决方案1】:

发生错误是因为您的宏包含分号。首先修复这些错误,您的代码将编译。

(我猜是发出了关于移位的警告,因为编译器看到类似1ull &lt;&lt; 64; - 1的东西。真正的错误是分号,但也会发出移位64位的警告。)

另外,请与类型一致。在您的短 sn-p 中,您混合使用 unsigned long、unsigned long long (ULL) 和 long。

【讨论】:

  • define 不是语句,因此除非在某些情况下,否则不应包含分号
  • @Lưu Vĩnh Phúc:我没说#define 是一个声明,对吗?预处理器宏#define 一个文本替换。最好让它们的实例表现得像 C 常量或函数调用,这意味着分号(如果有)进入宏实例附近的 C 代码,而不是宏本身。
  • @Lưu Vĩnh Phúc:我明白了。谢谢。
【解决方案2】:

我不确定您为什么需要使用位移位方法。 考虑简单地将一个非常大的 -1 转换为您的无符号类型,如下面的LARGEST_VALUE_3 所示。我认为您要选择 LARGEST_VALUE_2LARGEST_VALUE_1 是完全错误的(但之前建议过)。

#include <stdio.h>
#include <stdint.h>

typedef uint64_t ulong; /* Use of uint32_t, uint16_t, or uint8_t are recommended */

#define NUM_BITS        (sizeof(ulong) * 8)
#define LARGEST_VALUE_1 (1ULL << (NUM_BITS-1)) /* This answer is wrong */
#define LARGEST_VALUE_2 ((1ULL << NUM_BITS)-1) /* This answer is sometimes correct (except when NUM_BITS is >= 64) */
#define LARGEST_VALUE_3 ((ulong)(-1LL))        /* This is a simple answer */

int main(int argc, char* argv[])
{
  printf("Bits in ULONG %u\n", NUM_BITS);
  printf("Large value 1 is %llu\n", LARGEST_VALUE_1);
  printf("Large value 2 is %llu\n", LARGEST_VALUE_2);
  printf("Large value 3 is %llu\n", LARGEST_VALUE_3);
  return 0;
}

程序输出为:

Bits in ULONG 64
Large value 1 is 9223372036854775808
Large value 2 is 18446744073709551615
Large value 3 is 18446744073709551615

【讨论】:

  • 你不能在一个术语中使用像ulong这样的类型(或typedef)。
  • LARGEST_VALUE_3 取决于实现定义的行为,不是吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-04-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-06-24
相关资源
最近更新 更多