Reputation: 10126
I have variable that must be 16 bit long. How should I define it to be exactly 16 bit independently on the platform?
I can define it as short
, but depending on the platform it can be 16 bits or more.
Upvotes: 0
Views: 119
Reputation: 44240
if <stdint.h>
and int16_t
are not available, a workaround could be a bitfield. Since a bitfield is only valid inside a struct or union, it has to be wrapped into one:
#include <stdio.h>
struct auw {
int sixteen :16;
};
int main(void)
{
struct auw one = {16*1024 }, two, result;
two = one; /* assigmment is easy*/
/* but addition is a bit more painful */
result.sixteen = one.sixteen + two.sixteen -1;
printf("Result=%d\n", (int) result.sixteen );
return 0;
}
Upvotes: 0
Reputation: 272487
Assuming you're using C99, then use uint16_t
(or int16_t
) from <stdint.h>
. These are guaranteed to exist so long as the compiler has an underlying 16-bit type available.
Upvotes: 6
Reputation: 726
If you want a portable unsigned 16-bit integer, use uint16_t
and for signed 16-bit integer, use int16_t
.
inttypes.h
and stdint.h
are both introduced in C99
. If you are using C89
, you have to define your own type.
Upvotes: 0
Reputation: 122383
Use int16_t
for signed integer or uint16_t
for unsigned, The header inttypes.h
and stdint.h
are introduced in C99. If you are using C89, define your own type.
Note that they may not be provided in certain implementation, according to C11(ISO/IEC 9899:201x) §7.20 Integer types
For each type described herein that the implementation provides) shall declare that typedef name and define the associated macros. Conversely, for each type described herein that the implementation does not provide, shall not declare that typedef name nor shall it define the associated macros. An implementation shall provide those types described as ‘‘required’’, but need not provide any of the others (described as ‘optional’’).
Upvotes: 1