prepare to upload
[debian/gcpegg] / byteorder.h
1 /*
2
3         Byte-order invariant definitions
4
5 */
6
7 /*  The following macros allow packing fields of various types
8     into a byte-oriented packet with a running pointer named
9     pktP.  The reason we store then memcpy rather than storing
10     through a cast of pktP to the desired type is that the
11     latter approach can result in alignment faults when run
12     on RISC machines which typically require values to be
13     aligned at an even multiple of their length.  */
14
15 #define pack16(x) { \
16                         uint16 s = htons((uint16) (x)); \
17                         memcpy(pktP, &s, sizeof(uint16)); \
18                         pktP += sizeof(uint16); \
19                      }
20
21 #define pack32(x) { \
22                         uint32 i = htonl((uint32) (x)); \
23                         memcpy(pktP, &i, sizeof(uint32)); \
24                         pktP += sizeof(uint32); \
25                     }
26
27 #define pack8(x) { \
28                         char c = (x); \
29                         memcpy(pktP, &c, sizeof(char)); \
30                         pktP += sizeof(char); \
31                     }
32
33 #define pack8s(x, n) { \
34                             memcpy(pktP, x, n); \
35                             pktP += n; \
36                         }
37
38 /*  These macros unpack fields of various lengths from a
39     byte-packet packet in network byte order pointed to by
40     pktP.  Note that the argument of these macros must be
41     an lvalue.  */
42
43 #define unpack16(x) { \
44                             uint16 s; \
45                             memcpy(&s, pktP, sizeof(uint16)); \
46                             pktP += sizeof(uint16); \
47                             x = ntohs(s); \
48                        }
49
50 #define unpack32(x) { \
51                            uint32 i; \
52                            memcpy(&i, pktP, sizeof(uint32)); \
53                            pktP += sizeof(uint32); \
54                            x = ntohl(i); \
55                       }
56
57 #define unpack8(x) { \
58                         *((char *) &x) = (char) *pktP++; \
59                       }
60
61 #define unpack8s(x, n) { \
62                             memcpy(x, pktP, n); \
63                             pktP += n; \
64                           }