Re: How to use bitfields?
- From: "J. J. Farrell" <jjf@xxxxxxxxxx>
- Date: 18 Feb 2007 23:38:31 -0800
On Feb 18, 8:24 am, Radamanthe <tek...@xxxxxxxxxxxxxxxx> wrote:
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.red = 20;
pixel.u.comp.green = 22;
pixel.u.comp.blue = 7;
pixel.u.comp.alpha = 1;
printf( "red: %d, green: %d, blue: %d, alpha: %d\n",
pixel.u.comp.red,
pixel.u.comp.green,
pixel.u.comp.blue,
pixel.u.comp.alpha );
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.
.
- Follow-Ups:
- Re: How to use bitfields?
- From: Radamanthe
- Re: How to use bitfields?
- References:
- How to use bitfields?
- From: cman
- Re: How to use bitfields?
- From: Radamanthe
- How to use bitfields?
- Prev by Date: Re: anti-aliasing
- Next by Date: Re: Requesting advice how to clean up C code for validating string represents integer
- Previous by thread: Re: How to use bitfields?
- Next by thread: Re: How to use bitfields?
- Index(es):
Relevant Pages
|