This is the mail archive of the
gcc-help@gcc.gnu.org
mailing list for the GCC project.
Network/Host byte ordering and bitfields
- From: "Marcio O. Buss" <marcio at cs dot columbia dot edu>
- To: gcc-help at gcc dot gnu dot org
- Date: Wed, 23 Jun 2004 16:13:27 -0400 (EDT)
- Subject: Network/Host byte ordering and bitfields
Hi all,
I am trying to use the functions "ntohl" and "htonl"
in order to do byte-order swapping common to network
applications. However, the actual data structures I
have to byte-swap are of the form:
struct A {
unsigned int a : 1;
unsigned int b : 26;
unsigned int c : 3;
}__attribute__((packed));
i.e., they contain bitfields. If they didn't, I believe I
could simply say:
struct A v;
:
ntohl(v.a); ntohl(v.b); ntohl(v.c);
:
However, it turns out that bitfields are somehow non-portable.
I.e., if I initialize "v.a=0x1; v.b=0x2465464; and v.c = 0x5;"
and assume a little endian mode, the bits would laid out in a
memory word like:
v.c v.b v.a
| | |
XX 101 10 0100 0110 0101 0100 0110 0100 1
BYTE 3 BYTE 2 BYTE 1 BYTE 0
In big endian mode what I'd have is:
v.c v.a
| |
100 101 XX 10001100 11001010 1 1001000
| | | |
v.b(2:0) v.b(10:3) v.b(18:11) v.b(25:19)
BYTE 3 BYTE 2 BYTE 1 BYTE 0
where v.b(m:n) represents the "m-th" and "n-th" bits
in the original layout (Actually, the correct way to
write big endian would be "byte 0 byte 1 byte 2 byte 3",
or 1 1001000 11001010 10001100 100 101 XX
| |
v.a v.b v.c
The question is: is there any kind of support for this
type of issue, i.e., byte swapping in the presence of
bitfields? Any pointers to some sort of implementation?
Any help of how this could be done efficiently "by hand"?
Thanks a lot,
-Marcio.