Sam \(rép. sans -no-sp-am\) said:
Hi all !
I am new to C, sorry for those two questions ...
First, I would like to know which command allows me to test just one bit
from a char variable.
Second, I would like to programm a code checker. My code is 36 bits long,
but I can't do a bit-array or pointer (my compiler doesn't accept it). How
could I build one ? Could you give me a few commands to help me ??
Thanks a LOT !
Sam
To add to all the previous answers, there is one more method you could
explore. Enter bit fields:
struct bits {
unsigned field1 : 1; /* field1 is 1 bit long */
unsigned field2 : 7; /* field2 is 7 bits long */
unsigned field3 : 3; /* field3 is 3 bits long */
};
You can define the following structure to represent a 36-bit code:
typedef struct {
unsigned bit00:1, bit01:1, bit02:1, bit03:1, bit04:1,
bit05:1, bit06:1, bit07:1, bit08:1, bit09:1,
bit10:1, bit11:1, bit12:1, bit13:1, bit14:1,
bit15:1, bit16:1, bit17:1, bit18:1, bit19:1,
bit20:1, bit21:1, bit22:1, bit23:1, bit24:1,
bit25:1, bit26:1, bit27:1, bit28:1, bit29:1,
bit30:1, bit31:1, bit32:1, bit33:1, bit34:1,
bit35:1;
} Code;
You use a bit field as you would any other integral type, e.g.:
Code c;
/* code initialization goes here */
if (c.bit15) {
/* bit 15 was 1, do something */
} else {
/* bit 15 was zero, do something else */
}
The drawback of this approach is that since each of the bit fields
must be accessed explicitly in code (no bit field arrays are
possible,) such a representation could quickly get tedious to manage,
depending on the task at hand. To possibly speed things up a bit, you
can overlay the bit fields with a char array (let's assume that your
char is 8 bits long so that you need 5 chars to cover the 36 bits.)
Some operations (like copying the codes) can then be performed using a
loop on the char array.
typedef union {
struct {
unsigned bit00:1, bit01:1, bit02:1, bit03:1, bit04:1,
bit05:1, bit06:1, bit07:1, bit08:1, bit09:1,
bit10:1, bit11:1, bit12:1, bit13:1, bit14:1,
bit15:1, bit16:1, bit17:1, bit18:1, bit19:1,
bit20:1, bit21:1, bit22:1, bit23:1, bit24:1,
bit25:1, bit26:1, bit27:1, bit28:1, bit29:1,
bit30:1, bit31:1, bit32:1, bit33:1, bit34:1,
bit35:1;
} bits;
unsigned char chars[5];
} Code;
Look up more info on bit fields and unions to shed more light on this
approach.
Just my $0.02.
Lukasz