Re: endian conversions
- From: Ben Bacarisse <ben.usenet@xxxxxxxxx>
- Date: Tue, 25 Sep 2007 23:52:51 +0100
fbombd@xxxxxxxxx writes:
Standard data type conversions are fairly straight forward but how do
I handle user defined data types with bit fields and fields that cross
boundaries(word, half-word)? Eg/
struct Foo_t{
int f1:1;
int f2:3;
int f3:4;
int f4:24;
};
What needs to be swapped, if anything, for fields f1, f2, && f3 going
from one endian to the other?
Will f4 cause problems? I haven't done this in a while, and the last
time was in Ada95, but I could swear that fields that don't line up on
word and half-word boundaries gave me sigsegv's.
This has not been answered so I'll say a few words... You have a
problem because, I suspect, you are imagining a bad solution! There
is not much wrong with the above struct (provided your compiler allows
a bit field to be 24 bits wide). Unsigned int is a better type for
bit fields, but that is minor point. Any problems come from that way
you are imagining getting the data into and maybe out of it.
If you read and write the fields as decimal values, there will be no
endian or alignment issues. In other words, the trouble is in the code
you have not posted. If you are doing this:
char buf[SOME_SIZE];
...
struct Foo_t *fp = (struct Foo_t *)buf;
or, somewhat similarly,
struct Foo_t buffer;
...
get_data_from_big_bad_wold(&buffer, sizeof buffer);
then you have a whole host of troubles. Not least is the fact that
the you have no say over how the structure is layed out. You need to
ensure that structure is being layout how you want or you should
access the data some other way (like shifts and masks).
If you are sure the structure solution is as portable as you need it
to be, then you should solve the endian problem by treating the data
as bytes (say by reading it into a char array and swapping that before
treating the data as a struct Foo_t).
--
Ben.
.
- References:
- endian conversions
- From: fbombd
- endian conversions
- Prev by Date: Re: Where does programming begin?
- Next by Date: Re: Looking for a file format
- Previous by thread: endian conversions
- Next by thread: Re: the AIM of LIFE
- Index(es):
Relevant Pages
|