C/C++ Programmer's Guide (G06.27+, H06.03+)

Table Of Contents
Handling TNS Data Alignment
HP C/C++ Programmer’s Guide for NonStop Systems429301-010
23-10
C/C++ Misalignment Examples
Example 23-6. C/C++ External Structure With Misaligned Parts (Item 8)
Change this:
/* An interface as declared and used on 8-bit CPUs: */
struct {
short a; /* offset 0 */
char b; /* offset 2 */
short c; /* offset 3 */ /* moves to offset 4 on TNS */
} s;
i = s.c;
s.c = j;
To this:
struct {
short a; /* offset 0 */
char b; /* offset 2 */
unsigned char c[2]; /* represents an unaligned short */
} s;
#define get_short(var) ((short) ((var[0] << 8) | var[1]))
#define put_short(var,val) {var[0] = (val) >> 8; var[1] = (val);}
get_short(s.c);
put_short(s.c, j);
Example 23-7. C/C++ Check-Sum Function (Item 2, Item 9)
Change this:
char *name;
int lth;
unsigned short checksum = 0;
while (lth >= 2) {
checksum += * (short *) name; /* misalignment traps here */
name += 2; lth -= 2;
}
if (lth > 0) checksum += *name << 8;
To this:
char *name;
int lth;
unsigned short checksum = 0;
while (lth >= 2) {
checksum += (name[0] << 8) | name[1];
name += 2; lth -= 2;
}
if (lth > 0) checksum += *name << 8;