473,545 Members | 1,839 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How to use bitfields?

Who can explain to me what bitfields are and how to use them in
practice? I would need a fairly detailed explaination, I would be a
newbie to advanced C programming features. What are the advantages of
using bitfields?

cman

Feb 18 '07 #1
9 19246
cman wrote:
Who can explain to me what bitfields are and how to use them in
practice? I would need a fairly detailed explaination, I would be a
newbie to advanced C programming features. What are the advantages of
using bitfields?
A bit field is an element of a struct or union, having an
integer type but a specified "width," or number of bits. You
can have, for example, a three-bit signed integer or a five-bit
unsigned integer, and so on. There are restrictions on what
"underlying types" can be used, and on what widths are possible.
Also, it is not possible to form a pointer to a bit field (hence,
it is not possible to create an array of bit fields).

Bit fields have few advantages in portable code. In non-
portable code they are sometimes used to build a struct whose
layout corresponds to an externally-defined format of some
kind (e.g., the sign, exponent, and significand of a `float').

Recommendation: Learn to recognize them in code you read,
because you will encounter them, but avoid them in new code
that you write.

--
Eric Sosman
es*****@acm-dot-org.invalid
Feb 18 '07 #2
cman wrote:
Who can explain to me what bitfields are and how to use them in
practice? I would need a fairly detailed explaination, I would be a
newbie to advanced C programming features.
Bitfields are not an "advanced" feature of C. In fact, there is not much
difference with other integer types beside their bit size.
What are the advantages of using bitfields?
Memory usage, essentially, at the very lowest possible level. Note that
we could always do without bitfields anyway (by using bitwise operators
like & and |). It's just for readability that bitfields are used.

They are often used to provide an intuitive interface to an underlying
IO register or low-level structure. This way, you use the same semantic
to access values as any other type. Consider, as an example, a pixel
definition in some 16 bits ARGB format:

#include <stdio.h>
#include <stdint.h// C99 uint16_t

struct ARGB1555 {
union {
uint16_t value;
struct {
unsigned int blue : 5;
unsigned int green : 5;
unsigned int red : 5;
unsigned int alpha : 1;
} comp;
} u;
};

int main(void)
{
struct ARGB1555 pixel;
pixel.u.comp.re d = 20;
pixel.u.comp.gr een = 22;
pixel.u.comp.bl ue = 7;
pixel.u.comp.al pha = 1;
printf( "red: %d, green: %d, blue: %d, alpha: %d\n",
pixel.u.comp.re d,
pixel.u.comp.gr een,
pixel.u.comp.bl ue,
pixel.u.comp.al pha );

return 0;
}

This is far more readable than this uggly equivalent machine dependant crap:

int main(void)
{
struct ARGB1555 pixel;
pixel.u.value = (1 << 15) | (20 << 10) | (22 << 5) | 7;
printf( "red: %d, green: %d, blue: %d, alpha: %d\n",
(pixel.u.value >10) & 0x1f,
(pixel.u.value >5) & 0x1f,
pixel.u.value & 0x1f,
(pixel.u.value >15) & 0x1 );

return 0;
}

Of course, you may use constants for components instead of bare
hardcoded values (so porting the code would just have to redefine them,
like bitfields), but anyway this would still make the code harder to
read and even a lot harder to write.

Also, think about integer operations... even the simplest would be a
bargain without bitfields. Just consider:

pixel.u.comp.bl ue += 12;

Doing this simple operation without bitfields should be done with great
care in complex and hard to read expressions. Most programmers would
certainly introduce a temporary variable to handle it more easily, but
still. By using bitfields, you make the code a lot more readable while
the compiler takes care of all the masking and shifting bargain.

--
R.N.
Feb 18 '07 #3
Radamanthe <te****@free.de leteme.frwrites :
cman wrote:
>Who can explain to me what bitfields are and how to use them in
practice? I would need a fairly detailed explaination, I would be a
newbie to advanced C programming features.

Bitfields are not an "advanced" feature of C. In fact, there is not
much difference with other integer types beside their bit size.
>What are the advantages of using bitfields?

Memory usage, essentially, at the very lowest possible level. Note
that we could always do without bitfields anyway (by using bitwise
operators like & and |). It's just for readability that bitfields are
used.

They are often used to provide an intuitive interface to an underlying
IO register or low-level structure. This way, you use the same
semantic to access values as any other type. Consider, as an example,
a pixel definition in some 16 bits ARGB format:
[snip]

Yes, that kind of thing is common -- but it only works if the compiler
lays out your bit fields in exactly the way you need it to, matching
the externally imposed data layout. The standard says very little
about how bit fields are laid out. On the other hand, for this kind
of low-level code, depending on the behavior of a particular compiler
(which likely does document how it lays out bit fields) may not be a
problem.

--
Keith Thompson (The_Other_Keit h) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <* <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Feb 18 '07 #4
On Feb 18, 11:24 pm, Radamanthe <tek...@free.de leteme.frwrote:
...Note that
we could always do without bitfields anyway (by using bitwise operators
like & and |). It's just for readability that bitfields are used.
The compiler Sun used for the 68020 would use
the 68020's special bit-field op-codes for bitfields,
but not for the &/| equivalents. Any other compilers?

James

Feb 19 '07 #5
On Feb 18, 8:24 am, Radamanthe <tek...@free.de leteme.frwrote:
cman wrote:
What are the advantages of using bitfields?

Memory usage, essentially, at the very lowest possible level. Note that
we could always do without bitfields anyway (by using bitwise operators
like & and |). It's just for readability that bitfields are used.

They are often used to provide an intuitive interface to an underlying
IO register or low-level structure. This way, you use the same semantic
to access values as any other type. Consider, as an example, a pixel
definition in some 16 bits ARGB format:

#include <stdio.h>
#include <stdint.h// C99 uint16_t

struct ARGB1555 {
union {
uint16_t value;
struct {
unsigned int blue : 5;
unsigned int green : 5;
unsigned int red : 5;
unsigned int alpha : 1;
} comp;
} u;

};

int main(void)
{
struct ARGB1555 pixel;
pixel.u.comp.re d = 20;
pixel.u.comp.gr een = 22;
pixel.u.comp.bl ue = 7;
pixel.u.comp.al pha = 1;
printf( "red: %d, green: %d, blue: %d, alpha: %d\n",
pixel.u.comp.re d,
pixel.u.comp.gr een,
pixel.u.comp.bl ue,
pixel.u.comp.al pha );

return 0;

}

This is far more readable than this uggly equivalent machine dependant crap:

int main(void)
{
struct ARGB1555 pixel;
pixel.u.value = (1 << 15) | (20 << 10) | (22 << 5) | 7;
printf( "red: %d, green: %d, blue: %d, alpha: %d\n",
(pixel.u.value >10) & 0x1f,
(pixel.u.value >5) & 0x1f,
pixel.u.value & 0x1f,
(pixel.u.value >15) & 0x1 );

return 0;

}
Why do you describe the second version as "machine dependent crap"?
Your use of bitfields in the first example is entirely implementation
dependent, since very little about the layout of bitfields is defined
in C. One compiler may lay them out from the most significant bit
down, another from the least significant up, for example. If you do
this with bitfields, you may need to re-implement your code for each
different compiler or target.

The second method, however, is implementation and machine independent
and entirely portable (in principle - I've not checked the details of
your example). Code written in this way is portable between compilers
for the same target, and often across different targets.

Feb 19 '07 #6
J. J. Farrell wrote:
On Feb 18, 8:24 am, Radamanthe <tek...@free.de leteme.frwrote:
>cman wrote:
>>What are the advantages of using bitfields?
Memory usage, essentially, at the very lowest possible level. Note that
we could always do without bitfields anyway (by using bitwise operators
like & and |). It's just for readability that bitfields are used.

They are often used to provide an intuitive interface to an underlying
IO register or low-level structure. This way, you use the same semantic
to access values as any other type. Consider, as an example, a pixel
definition in some 16 bits ARGB format:

#include <stdio.h>
#include <stdint.h// C99 uint16_t

struct ARGB1555 {
union {
uint16_t value;
struct {
unsigned int blue : 5;
unsigned int green : 5;
unsigned int red : 5;
unsigned int alpha : 1;
} comp;
} u;

};

int main(void)
{
struct ARGB1555 pixel;
pixel.u.comp.re d = 20;
pixel.u.comp.gr een = 22;
pixel.u.comp.bl ue = 7;
pixel.u.comp.al pha = 1;
printf( "red: %d, green: %d, blue: %d, alpha: %d\n",
pixel.u.comp.re d,
pixel.u.comp.gr een,
pixel.u.comp.bl ue,
pixel.u.comp.al pha );

return 0;

}

This is far more readable than this uggly equivalent machine dependant crap:

int main(void)
{
struct ARGB1555 pixel;
pixel.u.value = (1 << 15) | (20 << 10) | (22 << 5) | 7;
printf( "red: %d, green: %d, blue: %d, alpha: %d\n",
(pixel.u.value >10) & 0x1f,
(pixel.u.value >5) & 0x1f,
pixel.u.value & 0x1f,
(pixel.u.value >15) & 0x1 );

return 0;

}

Why do you describe the second version as "machine dependent crap"?
Because I was too lazy to write a more clean version, with mask and
shift constants instead of hardcoded values (so it would have the same
degree of portability than the bitfield version, at least).

The point was to demonstrate the readability of bitfields. I could have
gone a lot further.
Your use of bitfields in the first example is entirely implementation
dependent, since very little about the layout of bitfields is defined
in C.
Of course it is implementation dependent ! This is all about low-level
assumptions. But only THIS definition has to be changed, not the
potential thousands lines of code using it everywhere else.

There is simply no way in C or any other language (maybe fragment
shaders, but this is not as flexible as C) to make machine independant
code for such things, as for many others. If you want speed (and believe
me: you WANT speed when dealing with screen devices), this is the best &
least you can do because anyway, you know that it will have to be ported
to be efficient enough.
One compiler may lay them out from the most significant bit
down, another from the least significant up, for example. If you do
this with bitfields, you may need to re-implement your code for each
different compiler or target.
The bitfield definition code only. All the rest is unchanged and THAT is
the point.
The second method, however, is implementation and machine independent
and entirely portable (in principle - I've not checked the details of
your example).
No, it isn't (like the bitfield version) when you're not alone in your C
universe and you communicate with devices somewhere else millions of
times per second. C is not only about dealing with databases used by C
programs only. That would be so simple.

I don't use C because of its portability (though this is welcome), but
because it is the only language that allow me to do pseudo-assembly
low-level code very tied to the hardware in such a way that I don't have
to rewrite everything for each target. In my pov, it is the greatest
power of C and the main reason why I stick to it (or C++ eventually).
Code written in this way is portable between compilers
for the same target, and often across different targets.
Is this a debate around 99.98% versus 99.99% portability ? And what is a
target for you ? A "C machine" ? I wish computers to be only "C
machines", I would have far less problems, but halas, my output device
would not be able to draw pixels anyway, and this example would
certainly have no sense.

--
R.N.
Feb 19 '07 #7
Radamanthe <te****@free.de leteme.frwrites :
J. J. Farrell wrote:
[...]
>Your use of bitfields in the first example is entirely implementation
dependent, since very little about the layout of bitfields is defined
in C.

Of course it is implementation dependent ! This is all about low-level
assumptions. But only THIS definition has to be changed, not the
potential thousands lines of code using it everywhere else.

There is simply no way in C or any other language (maybe fragment
shaders, but this is not as flexible as C) to make machine independant
code for such things, as for many others. If you want speed (and
believe me: you WANT speed when dealing with screen devices), this is
the best & least you can do because anyway, you know that it will have
to be ported to be efficient enough.
<OT>
In fact, there are machine-independent ways to do this in *some*
languages. In Ada, for example, you can use a representation clauses
to specify the exact layout of a record (struct) type, or you can use
slices of a packed Boolean array.
</OT>

[...]
>Code written in this way is portable between compilers
for the same target, and often across different targets.

Is this a debate around 99.98% versus 99.99% portability ? And what is
a target for you ? A "C machine" ? I wish computers to be only "C
machines", I would have far less problems, but halas, my output device
would not be able to draw pixels anyway, and this example would
certainly have no sense.
Bit field layout is likely to be affected by byte ordering, which
definitely varies from one platform to another. I suspect there are
other variations beyond that, such as whether bit fields can cross a
word boundary, and just what a "word" is.

--
Keith Thompson (The_Other_Keit h) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <* <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Feb 19 '07 #8
Keith Thompson wrote:
Radamanthe <te****@free.de leteme.frwrites :
>J. J. Farrell wrote:
[...]
>>Your use of bitfields in the first example is entirely implementation
dependent, since very little about the layout of bitfields is defined
in C.
Of course it is implementation dependent ! This is all about low-level
assumptions. But only THIS definition has to be changed, not the
potential thousands lines of code using it everywhere else.

There is simply no way in C or any other language (maybe fragment
shaders, but this is not as flexible as C) to make machine independant
code for such things, as for many others. If you want speed (and
believe me: you WANT speed when dealing with screen devices), this is
the best & least you can do because anyway, you know that it will have
to be ported to be efficient enough.

<OT>
In fact, there are machine-independent ways to do this in *some*
languages. In Ada, for example, you can use a representation clauses
to specify the exact layout of a record (struct) type, or you can use
slices of a packed Boolean array.
</OT>
Nice. Is it easily merged into C code or should I rewrite everything in
Ada ? :)
>>Code written in this way is portable between compilers
for the same target, and often across different targets.
Is this a debate around 99.98% versus 99.99% portability ? And what is
a target for you ? A "C machine" ? I wish computers to be only "C
machines", I would have far less problems, but halas, my output device
would not be able to draw pixels anyway, and this example would
certainly have no sense.

Bit field layout is likely to be affected by byte ordering, which
definitely varies from one platform to another. I suspect there are
other variations beyond that, such as whether bit fields can cross a
word boundary, and just what a "word" is.
You can use padding fields to sort it out. That's not to say the
compiler would not be conform if it would not permit to represent the
required bits layout anyway, but it would be obsolete in the context of
adressing a given device at a such low level, thus losing a great
advantage of C.

--
R.N.
Feb 19 '07 #9
Radamanthe <te****@free.de leteme.frwrites :
Keith Thompson wrote:
[...]
><OT>
In fact, there are machine-independent ways to do this in *some*
languages. In Ada, for example, you can use a representation clauses
to specify the exact layout of a record (struct) type, or you can use
slices of a packed Boolean array.
</OT>

Nice. Is it easily merged into C code or should I rewrite everything
in Ada ? :)
<OT>
Ada provides mechanisms for interfacing to C. The syntax is very
different, so you can't mix them at the source level. An Ada frontend
is an optional part of gcc.

It's up to you (and entirely off-topic) whether you want to use Ada.
</OT>

[...]
>Bit field layout is likely to be affected by byte ordering, which
definitely varies from one platform to another. I suspect there are
other variations beyond that, such as whether bit fields can cross a
word boundary, and just what a "word" is.

You can use padding fields to sort it out. That's not to say the
compiler would not be conform if it would not permit to represent the
required bits layout anyway, but it would be obsolete in the context
of adressing a given device at a such low level, thus losing a great
advantage of C.
What do you mean by "padding fields"?

--
Keith Thompson (The_Other_Keit h) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <* <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Feb 20 '07 #10

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

Similar topics

2
3173
by: Grumfish | last post by:
In order to familiarize my self with Flash files and their bytecode I've started to make an assembler. My first problem is writing the bitfields the format uses often. It is a series of fields, each can be a different number of bits, combined into the least amount of bytes possible. Extra bits in the last byte are padded with zeros. I would...
3
3394
by: Jon Slaughter | last post by:
I'm using bit fields to compactly represent some data I need to manage and I've read that they are not portable. I don't understand why that is the case? As long as I don't "indirectly" mess with the fields and I go through the compiler and allow it to choose the appropriate way to handle them then why shouldn't it be ok? The whole point...
0
400
by: tmartsum | last post by:
I have a discussion in comp.std.c++ After a (bit stupid) suggestion on representing a fixed 'big' length int I moderated it to "Bitfields-ints should be allowed to have any fixed length" I got no replys on my moderated suggestion. (I am asking you your opinion of this - I do not really have a C++-problem)
8
1899
by: Régis Troadec | last post by:
Hi all, I follow c.l.c. for only a short time and I would like to know why there isn't anything concerning bitfields among the FAQs. Is it because ... 1. of portability issues? 2. bitfields aren't enough useful to be discussed? 3. of the low frequency of questions concerning this topic? 4. of anything else?...
23
2797
by: rohit | last post by:
Hi, In my couple of years of experience, I have never found a single instance where I needed to use unions and bitfields(though I have used structures).I was just imagining where would these find relevance.Though both of these(bitfields and unions) are used where space is a constraint(so I can assume always in embedded systems,where memory...
6
2673
by: GalenTX | last post by:
I am looking for opinions on a possible approach to coping with bitfields in a heterogenous environment. We've got a bunch of legacy code which maps to hardware using bitfields. The code was developed for a PowerPC/VxWorks/Tornado enviromant, with the bits packed in a big-endian manner: msb first. We now have to develop an...
19
14793
by: Mehta Shailendrakumar | last post by:
Hi, I would like to know why array of bitfields is not possible. Is there any relation with processor architecture for this? Thank you for your time. Regards, Shailendra
18
4691
by: richard_l | last post by:
Hello All, I am writing an application which receives a word which is a bitmap. I have created a word typedef which contains a bitfield defining each bit. however, I was wondering however if it would be better to write a macro to access each bit instead of the bitfield. I have read the C-FAQ on bit fields, but was wondering if there were...
10
8469
by: lithiumcat | last post by:
Hi, This question seems to come up quite often, however I haven't managed to find an answer relevant to my case. I often use binary flags, and I have alaways used a "bitmask" technique, that is using #defined or const int powers of two, and using the following primitives : /* declaration and initizalisation of flags */ int flags = 0; /*...
0
7680
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
0
7934
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
0
6003
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
1
5349
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
4966
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3476
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
0
3459
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1908
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1033
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.