Re: How can I obtain 2 and 4-byte data types?

phil-news-nospam_at_ipal.net
Date: 08/25/03


Date: 25 Aug 2003 14:24:52 GMT

In comp.unix.programmer Dr. David Kirkby <drkirkby@ntlworld.com> wrote:

| The code needs to write Bitmap files. The header of the bitmap needs
| numbers of 2 and 4 bytes. They need to be written in little-endian
| format (as on Intel x86). Until yesterday, I was using using chars,
| shorts, and ints and having routines to convert between big and little
| endian. However, all my code falls to pieces if there is no data type
| with 2 and 4 bytes.
|
| Any suggestions how to create a data type of 2 and 4 types AND
| manipulate that data type in a way one can add and subtract with it,
| and still write it in big and little endian??

You actually have two problems, the need for integer sizes that are not
available, and the need for a specific byte order. You may be using
things like htons() and htonl() to get the byte order you want (but
those are for network byte order which is different than Intel byte
order).

The portable code which would let you store and fetch data under external
constraints of format would involve constructing or de-constructing using
the char types (signed or unsigned as appropriate). The external medium
is defined in terms of octets, so using buffers of arrays of octets and
working with those units to construct your data makes for portable code.

Of course, such portable code is not always the most optimal. Sometimes
the optimal way has been abstracted, like htons() and htonl(). And those
might be implemented differently on different machines. You'd have to go
to the same extreme if optimality is desired, unless you can match your
needs with existing abstractions (which I doubt).

| I know I can do
|
| char foo[2], foobar[4];
|
| but that is not very convenient.

Portability isn't. You can also do this with shifting, but I think you
will find that to be even less convenient.

Maximize your convenience by creating abstractions that let you work in
the defined units, but which operate in chars/octets underneath. Later,
you can go back and create more optimal implementations for specific
platform architectures.

-- 
-----------------------------------------------------------------------------
| Phil Howard KA9WGN       | http://linuxhomepage.com/      http://ham.org/ |
| (first name) at ipal.net | http://phil.ipal.org/   http://ka9wgn.ham.org/ |
-----------------------------------------------------------------------------