How to declare variable of fixed size across all platforms?


E

EricFowler

Sorry if this is a FAQ, I could not find it.

I am writing C code that will be reading data of fixed format from
devices. The format of this data is constant and beyond my control and
comprises 8, 16, and 32 bit signed and unsigned values.

I wish to write C code that will compile on all (well, many)
platforms, and will have properly sized variables. The problem is in
declaring a variable that is always (say) 16 unsigned bits.

A first cut is to use __uint16_t , but I have been having a hard time
defining that variable. It is supposedly in stdint.h but when I
include that file, the type is undefined.

I have noticed that when I include stdio.h, the type is found, but I
don't want that header everywhere.

What is the simple standard way to define a variable of fixed bit
size?

Don't worry about endianess; I will deal with that separately.

Thanks

Eric
 
Ad

Advertisements

J

James Kanze

Sorry if this is a FAQ, I could not find it.
I am writing C code that will be reading data of fixed format
from devices. The format of this data is constant and beyond
my control and comprises 8, 16, and 32 bit signed and unsigned
values.

In what format? Size isn't the only aspect of representation
which varies.
I wish to write C code that will compile on all (well, many)
platforms, and will have properly sized variables. The problem
is in declaring a variable that is always (say) 16 unsigned
bits.

If you have the C99 standard header <stdint.h> (and most
compilers do), there are often types uint16_t, etc. available.
(They will be available if the platform has a type with the
corresponding size, without padding, and, in the case of signed
integers, uses 2's complement. Which covers a number of the
more wide spread general purpose computers, even if it doesn't
hold for some mainframes, embedded processors, or very old
systems.)

Having the right size, however, really only helps for unsigned
char; having 2's complement means that signed char can also be
read directly, but it stops there.
A first cut is to use __uint16_t,

Which is a compiler extension, if it exists.
but I have been having a hard time defining that variable. It
is supposedly in stdint.h but when I include that file, the
type is undefined.

The type in stdint.h is uint16_t.
I have noticed that when I include stdio.h, the type is found,
but I don't want that header everywhere.

In your particular implementation. Names beginning with two
underscores are reserved for the implementation, and are usually
used for things like library internals.
What is the simple standard way to define a variable of fixed
bit size?
Don't worry about endianess; I will deal with that separately.

The same solution which deals with endianess deals with
different representations and sizes---once you've dealt with
one, you should have dealt with all.
 

Top