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