"David Rager" <ra*****@nospammemail.utexas.edu> wrote in message news:<bp**********@geraldo.cc.utexas.edu>...
Howdy,
Put briefly, I have an array of chars, which I would like to access in pairs
of bytes via casting the array to an array of shorts. I'm trying to be as
elegant as possible.
Hi David,
Let me preface by saying that I'm not all that experienced with c++,
and so there may be other issues with what I'm about to write.
I had the need to do similar casting recently...I was accessing a char
array as an array of unsigned long ints. Someone raised the issue of
"alignment", which could present portability problems. The issue is
basically this. Suppose you have an array of 10 ints, a[10], and you
want to access the 2nd & 3rd bytes as a short (ie a[1] & a[2]). It is
possible that short can only be aligned with bytes that are an
even-multiple offset from the start of the memory space. That is,
your short int pointer can only point to(in char*) a[0], a[2], a[4],
a[6], a[8] indexed as ashort[0] - ashort[4].
What I ended up doing was to turn the problem around. I made a class,
AlignInt, that creates an empty int (or short) array, loads the
char-data into that array, and then give the user pointers to that
data as signed or unsigned char, short, int, and long. So...for
example, if I had the char string "abcdefgh" and I wanted to access
short int words from the same memory location as "bc", "de", "fg",
"hNULL", (note this case doesn't use the first byte...this is the sort
of case that could cause alignment issues). I first create an empty
4-word array of short, cast the array to char*, load the substring
"bcdefgh" into the array, then safely access as either data-type.
Anyway...just food for thought. If you want to see or use this class,
just ask. It accepts string, a file, or an existing aligned array,
and gives public access to the data and array length represented as
any of the native data-types.