473,324 Members | 2,567 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,324 software developers and data experts.

What's the memory layout of bit field struct in little-endian and big-endian platform?

Given the bit field struct:

int main()
{
union
{
struct
{
unsigned short s1 : 4;
unsigned short s2 : 3;
unsigned short s3 : 2;
} x;
char c;
} v;
v.c = 0x7A; // 0111 1010 b
printf( "%X", v.x.s3 );
}

What's the memory layout of bit field struct v after set v.c=0x7A in
little-endian platform and big-endian platform?

Oct 19 '05 #1
8 17531
aling wrote:
Given the bit field struct:

int main()
{
union
{
struct
{
unsigned short s1 : 4;
unsigned short s2 : 3;
unsigned short s3 : 2;
} x;
char c;
} v;
v.c = 0x7A; // 0111 1010 b
printf( "%X", v.x.s3 );
}

What's the memory layout of bit field struct v after set v.c=0x7A in
little-endian platform and big-endian platform?


It is unspecified and implementation-dependent. You should avoid
bitfields in C++ because:

1. They are non-portable, as you seem to have learned the hard way.
C++ARM says that the layout of bit-fields "is highly implementation
dependent, and it is wise not to make any assumptions about it unless
absolutely necessary." On a previous project, we used bit-fields for
mapping the contents of hardware registers, but when we eventually
ported the project to another platform with the other endianness, we
had to manually reverse the order of our many bit-fields. If I had time
and was still working on that project, I might try to use template
metaprogramming (a la Boost and Modern C++ Design) to engineer a more
portable solution akin to the Boost Parameter library
(http://boost.org/libs/parameter/doc/html/index.html). (N.B., I haven't
looked to see if anything like that already exists, and you might want
to. Compare this article discussing bitstreams in C++
http://www.cuj.com/documents/s=9897/...510bishop.html .)

2. Some programmers mistakenly see bit-fields as a good form of space
or speed optimization. Consult C++ARM section 9.6 and C++PL section
C.8.1 for reasons why these forms of premature optimization often have
the opposite effect. In certain scenarios, bandwidth bottlenecks
*might* be eased by bit-packing. Just remember not to prematurely
optimize (http://www.gotw.ca/publications/mill09.htm). :-)

Cheers! --M

Oct 19 '05 #2
aling wrote:

What's the memory layout of bit field struct v after set v.c=0x7A in
little-endian platform and big-endian platform?


The C and C++ languages both say that after you've assigned to one
member of a union you can't read from other members. The behavior of
your code is undefined.

The other issue is that the layout of bitfields is
implementation-defined. Read your compiler's documentation to see what
they do.

--

Pete Becker
Dinkumware, Ltd. (http://www.dinkumware.com)
Oct 19 '05 #3
mlimber wrote:

It is unspecified and implementation-dependent. You should avoid
bitfields in C++ because:
You should use bitfields when they are appropriate.

1. They are non-portable,
Yes, that is correct. When you need 'em you need 'em. Non-portable is
often far more useful than strictly conforming code that doesn't
actually work with some compilers.
as you seem to have learned the hard way.
Well, more important is the misuse of the union.
C++ARM says that the layout of bit-fields "is highly implementation
dependent, and it is wise not to make any assumptions about it unless
absolutely necessary." On a previous project, we used bit-fields for
mapping the contents of hardware registers, but when we eventually
ported the project to another platform with the other endianness, we
had to manually reverse the order of our many bit-fields. If I had time
and was still working on that project, I might try to use template
metaprogramming (a la Boost and Modern C++ Design) to engineer a more
portable solution akin to the Boost Parameter library
(http://boost.org/libs/parameter/doc/html/index.html). (N.B., I haven't
looked to see if anything like that already exists, and you might want
to. Compare this article discussing bitstreams in C++
http://www.cuj.com/documents/s=9897/...510bishop.html .)


It's much simpler to just rewrite the code that needs to be changed.
It's not that big. Portability is about being able to move across
platforms easily, and that means isolating platform-dependent code so
that it's easily identified and easily modified. Of course, that's
Old-Fashioned Design (TM), and I'm sure you can have much more fun, and
spend far more time, writing meta-programmed monstrosities that do part
of the job. Personally, I prefer productivity to cleverness.

--

Pete Becker
Dinkumware, Ltd. (http://www.dinkumware.com)
Oct 19 '05 #4
Pete Becker wrote:
mlimber wrote: [snip]
C++ARM says that the layout of bit-fields "is highly implementation
dependent, and it is wise not to make any assumptions about it unless
absolutely necessary." On a previous project, we used bit-fields for
mapping the contents of hardware registers, but when we eventually
ported the project to another platform with the other endianness, we
had to manually reverse the order of our many bit-fields. If I had time
and was still working on that project, I might try to use template
metaprogramming (a la Boost and Modern C++ Design) to engineer a more
portable solution akin to the Boost Parameter library
(http://boost.org/libs/parameter/doc/html/index.html). (N.B., I haven't
looked to see if anything like that already exists, and you might want
to. Compare this article discussing bitstreams in C++
http://www.cuj.com/documents/s=9897/...510bishop.html .)


It's much simpler to just rewrite the code that needs to be changed.
It's not that big. Portability is about being able to move across
platforms easily, and that means isolating platform-dependent code so
that it's easily identified and easily modified.


Ease of rewriting is application-specific, methinks. If there are a
multiplicity of bit-field structures and several varying compiler
implementations that they need to work with, things can get ugly for
several reasons. Rewriting will probably entail a lot of error-prone
cut-and-pasting, and it should be noted that it's difficult to write
test code for such things because that test code would also vary
between platforms. So, I would argue that it could be a big deal after
all, especially for mission-critical type work.
Of course, that's
Old-Fashioned Design (TM), and I'm sure you can have much more fun, and
spend far more time, writing meta-programmed monstrosities that do part
of the job. Personally, I prefer productivity to cleverness.


Well, I should first probably confess that I have used bit-fields
myself since working on the aforementioned project, but I did so mainly
because I lacked a better facility and didn't have time to metaprogram
one. I wish I had such a library, though, because it would allow me to
drop bit-fields altogether and have a portable (in the sense that it
compiles and works without modification) with a wide variety of
platforms and compilers. If such a library existed, many embedded
programmers would be saved a lot of dull, error-prone porting work.

Cheers! --M

Oct 19 '05 #5
aling wrote:
Given the bit field struct:

int main()
{
union
{
struct
{
unsigned short s1 : 4;
unsigned short s2 : 3;
unsigned short s3 : 2;
} x;
char c;
} v;
v.c = 0x7A; // 0111 1010 b
printf( "%X", v.x.s3 );
}

What's the memory layout of bit field struct v after set v.c=0x7A in
little-endian platform and big-endian platform?


Being implementation-dependent, the layout of the bitfield does not
conform to any one standard. In fact, a bitfield may be laid out the
same way on both big-endian and little-endian machines. Metrowerks
CodeWarrior, for example, has a #pragma reverse_bitfields that does
exactly that. (you may wonder who needs such a pragma - this pragma was
added so that Microsoft could compile Macintosh Office with
CodeWarrior).

Greg

Oct 19 '05 #6
mlimber wrote:

Ease of rewriting is application-specific, methinks.
Obviously.
If there are a
multiplicity of bit-field structures and several varying compiler
implementations that they need to work with, things can get ugly for
several reasons. Rewriting will probably entail a lot of error-prone
cut-and-pasting,
Properly designed macros are usually a better solution than cut-and-paste.
and it should be noted that it's difficult to write
test code for such things because that test code would also vary
between platforms. So, I would argue that it could be a big deal after
all, especially for mission-critical type work.

Yes, writing portable code isn't trivial. Neither is meta-programming.
Either way, though, you damned well better be able to test what you've
done. "It's too hard" doesn't cut it.
Of course, that's
Old-Fashioned Design (TM), and I'm sure you can have much more fun, and
spend far more time, writing meta-programmed monstrosities that do part
of the job. Personally, I prefer productivity to cleverness.

Well, I should first probably confess that I have used bit-fields
myself since working on the aforementioned project, but I did so mainly
because I lacked a better facility and didn't have time to metaprogram
one.


You've just agreed with what I said. To put it more strongly: bitfields
work just fine for what they are designed to do. Which is probably why
there is no "better facility" through metaprogramming.
I wish I had such a library, though, because it would allow me to
drop bit-fields altogether and have a portable (in the sense that it
compiles and works without modification) with a wide variety of
platforms and compilers. If such a library existed, many embedded
programmers would be saved a lot of dull, error-prone porting work.


Well, maybe a small amount of moderately dull porting work. It's no more
error prone than relying on a library that attempts to detect the
essential criteria for laying out bit fields that are inherently
non-portable. And, of course, the way to make sure that porting the
bitfield code isn't error-prone is to write test cases, and use them.

--

Pete Becker
Dinkumware, Ltd. (http://www.dinkumware.com)
Oct 19 '05 #7
Pete Becker wrote:
mlimber wrote:

Ease of rewriting is application-specific, methinks.
Obviously.
If there are a
multiplicity of bit-field structures and several varying compiler
implementations that they need to work with, things can get ugly for
several reasons. Rewriting will probably entail a lot of error-prone
cut-and-pasting,


Properly designed macros are usually a better solution than cut-and-paste.


But then we're not talking about rewriting any more. Or, rather, we're
talking about rewriting the macros, and there's not so great a
difference in porting a preprocessor library and a metaprogrammed one.
and it should be noted that it's difficult to write
test code for such things because that test code would also vary
between platforms. So, I would argue that it could be a big deal after
all, especially for mission-critical type work.


Yes, writing portable code isn't trivial. Neither is meta-programming.
Either way, though, you damned well better be able to test what you've
done. "It's too hard" doesn't cut it.


Agreed.
Well, I should first probably confess that I have used bit-fields
myself since working on the aforementioned project, but I did so mainly
because I lacked a better facility and didn't have time to metaprogram
one.


You've just agreed with what I said. To put it more strongly: bitfields
work just fine for what they are designed to do. Which is probably why
there is no "better facility" through metaprogramming.


Perhaps, but the fact that this same question gets posted repeatedly on
this newsgroup may indicate a yearning of some kind. :-) (See also the
similar-but-different article in CUJ that I cited in my first post.)
I wish I had such a library, though, because it would allow me to
drop bit-fields altogether and have a portable (in the sense that it
compiles and works without modification) with a wide variety of
platforms and compilers. If such a library existed, many embedded
programmers would be saved a lot of dull, error-prone porting work.


Well, maybe a small amount of moderately dull porting work. It's no more
error prone than relying on a library that attempts to detect the
essential criteria for laying out bit fields that are inherently
non-portable. And, of course, the way to make sure that porting the
bitfield code isn't error-prone is to write test cases, and use them.


The metaprogrammed solution that I am thinking of would manually
assemble the "bit-field" inside a standard integral type with explicit
bit-twiddling operations and would thus avoid implementation
dependencies for bit-fields. There is no way to detect, say, endinaness
at compile-time, but a few simple tests run in a library configuration
should easily be able to determine the right compiler/processor
configuration (and that's true of a macro library or a metaprogrammed
one). The library should, of course, supply a thorough set of tests for
itself that can be run on each platform.

Cheers! --M

Oct 19 '05 #8
mlimber wrote:
Pete Becker wrote:
mlimber wrote:
Ease of rewriting is application-specific, methinks.


Obviously.

If there are a
multiplicity of bit-field structures and several varying compiler
implementations that they need to work with, things can get ugly for
several reasons. Rewriting will probably entail a lot of error-prone
cut-and-pasting,


Properly designed macros are usually a better solution than cut-and-paste.

But then we're not talking about rewriting any more. Or, rather, we'r
talking about rewriting the macros, and there's not so great a
difference in porting a preprocessor library and a metaprogrammed one.


I look forward to seeing your design for a metaprogrammed library that
manages bitfields. Until then, I'll continue to use macros.

--

Pete Becker
Dinkumware, Ltd. (http://www.dinkumware.com)
Oct 19 '05 #9

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

21
by: Rabbit63 | last post by:
Hi: I want to show a set of records in the database table on the clicnt browser. I have two ways to do this (writen in JScript): 1.The first way is: <% var sql = "select firstname from...
13
by: Vincezo Ciaschini | last post by:
Supposing you have the following declaration in a header file: -- head.h -- struct s { int c; char v; #if defined(__cplusplus) s(); s(double); method1(int);
140
by: Oliver Brausch | last post by:
Hello, have you ever heard about this MS-visual c compiler bug? look at the small prog: static int x=0; int bit32() { return ++x; }
100
by: E. Robert Tisdale | last post by:
What is an object? Where did this term come from? Does it have any relation to the objects in "object oriented programming"?
9
by: Andrew Au | last post by:
Dear all, I am trying to write a piece of software that use Object Oriented design and implement it with C, I did the following == In Object.h == typedef struct ObjectStructure* Object; ...
5
by: Mike | last post by:
Within the following structure, TopStruct, I'd like to create 3 other structures, 2 of which make up a union. The first structure will always contain some data that I need and should never be...
11
by: Henryk | last post by:
I have something like class Params { public: const static char nOne = 1; const static int nTwo = 2; const static char nThree = 3; }; This is just a wrapper for globally used parameters in...
5
by: .rhavin grobert | last post by:
let say i have struct SA { long l1; long l2: long l3; }; struct SB: public SA { long l4;
11
by: michelqa | last post by:
Hello, I can retrieve column text from a ListView in another process but I cant figure out how to access to structure elements (LVCOLUMN) <code> //Handle variable is a valid ListView handle ...
32
by: Stephen Horne | last post by:
I've been using Visual C++ 2003 for some time, and recently started working on making my code compile in GCC and MinGW. I hit on lots of unexpected problems which boil down to the same template...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.