Frage

I know this something that has been asked previously on stack overflow but I have tried everything suggested as a solution but nothing works. My problem is simple, I'm trying to define an unsigned long which must take the largest possible value allowed.

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

where ulong is typedef'ed as unsigned long. I get a warning that the left shift count >= width of type. I have checked the size of unsigned long on my 64-bit machine and it's 8B. Finally, I tried compiling with the -m64 flag, but all in vain.

Any ideas?

War es hilfreich?

Lösung 2

I am not sure why you need to do the bit shift approach. Consider simply casting a very large -1 to your unsigned type as shown by LARGEST_VALUE_3 below. I think you were going for LARGEST_VALUE_2 and LARGEST_VALUE_1 is simply wrong (but was suggested earlier).

#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;
}

Program output is:

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

Andere Tipps

The error occurs, because your macros include a semicolon. Fix these errors first and your code will compile.

(I guess the warning about the bit shift is issued, because the compiler sees something like 1ull << 64; - 1. The real error is the semicolon, but the warning for shifting by 64 bits is also issued.)

Also, please be consistent with the types. In your short snippet, you mix unsigned long, unsigned long long ( ULL) and long.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top