Re: Bit twiddling
- From: Paul Mesken <usurper@xxxxxxxxxx>
- Date: Fri, 03 Jun 2005 16:44:04 +0200
On Fri, 03 Jun 2005 16:36:51 +0530, grid <prohit99@xxxxxxxxx> wrote:
>> void print(struct twid *tw)
>> {
>> tw->bit1?printf("1"):printf("0");
>> tw->bit2?printf("1"):printf("0");
>> tw->bit3?printf("1"):printf("0");
>> tw->bit4?printf("1"):printf("0");
>> tw->bit5?printf("1"):printf("0");
>> tw->bit6?printf("1"):printf("0");
>> tw->bit7?printf("1"):printf("0");
>> tw->bit8?printf("1"):printf("0");
>> printf("\n");
>
>Is there any way to traverse through the member bitfields with a loop or
>is there a consise way to write the above stuff.
No, because you cannot have an array of bitfields (something like
"signed int Bit[8]:1;").
Just *don't* use bitfields in this case. You cannot know in which
order they are represented (left to right or right to left).
For example :
union
{
int MyInteger;
struct
{
unsigned int Bit1:1;
unsigned int Bit2:1;
....
unsigned int Bit8:1;
} Bits;
}MyUnion;
Let's say that the compiler stores your bitfields in an integer the
same size as MyInteger (but, in reality, you don't know this).
Still, you cannot be sure whether Bit1 is bit 0 of that integer or bit
31 (if int is 32 bits).
By the way : the least significant bit of some value is, typically,
not called "bit 1" but "bit 0".
The whole use of bitfields, in your case, is highly unportable. It
just might happen to work okay for your compiler (sheer luck) but on
another it might not work as you expected.
It's also not faster at all (if you thought it was). Behind the
scenes, the compiler is, typically, doing all kinds of masking,
shifting, etc. in order to use, store or read the bitfield.
Don't use bitfields just because they are part of C. There are better
ways (both portability- and performance-wise) to achieve what you want
to achieve and they have been posted.
Remember what K&R2 says about bitfields :
"Almost everything about fields is implementation-dependent.".
What you try to do depends on the implementation. That's a _bad_
programming habit that should be avoided.
.
- Follow-Ups:
- Re: Bit twiddling
- From: Keith Thompson
- Re: Bit twiddling
- From: Paul Mesken
- Re: Bit twiddling
- References:
- Bit twiddling
- From: grid
- Re: Bit twiddling
- From: grid
- Bit twiddling
- Prev by Date: Re: I think the question I just posted got lost.
- Next by Date: Re: Bit twiddling
- Previous by thread: Re: Bit twiddling
- Next by thread: Re: Bit twiddling
- Index(es):
Relevant Pages
|