Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculating and using maximum value of uint32_t

Tags:

c

gcc

c99

I know that UINT32_MAX exists, but I haven't been able to use it. I tried printf("%d\n", UINT32_MAX); and it printed out -1. Using %ld instead of %d presented me with the error that UINT32_MAX is of the type unsigned int and needs %d to print it out.

Please help, what I ideally want is a macro/enum that holds the maximum value of word_t which is a type defined by me which currently is uint32_t.

I hope that I made clear what I want, if not please feel free to ask.

EDIT

I forgot to say what I'm actually trying to do. All of this will be used to set an array of integers all to their maximum value, because that array of integers actually is a bitmap that will set all bits to 1.

like image 452
orlp Avatar asked Mar 04 '11 17:03

orlp


1 Answers

The portable way to print a uintN_t object is to cast it to a uintmax_t and use the j length modifier with the u conversion specifier:

printf("%ju\n", (uintmax_t)(UINT32_MAX));

The j means that the argument is either an intmax_t or a uintmax_t; the u means it is unsigned, so it is a uintmax_t.

Or, you can use the format strings defined in <inttypes.h> (n this case, you'd use PRIu32):

printf("%" PRIu32 "\n", UINT32_MAX);

You can't just use %u because it isn't guaranteed that int is represented by at least 32 bits (it only needs to be represented by at least 16 bits).

like image 70
James McNellis Avatar answered Sep 19 '22 06:09

James McNellis