ganeshredcobra
ganeshredcobra

Reputation: 2091

bit data type in C language

I want to create a bit datatye in c language. I tried creating it using a structure with bitfield

struct bittype {
    unsigned int value:1;
};
typedef struct bittype bit;

But the problem with this is I have to use variables like

bit statusVariable;
statusVariable.value = 1;

How can i define a variable directly like,

bit statusVariable;
statusVariable = 1;

Upvotes: 2

Views: 1268

Answers (1)

0___________
0___________

Reputation: 68034

Bits cannot be individually addressed only bytes.

struct bittype {
    unsigned int value:1;
};
typedef struct bittype bit;

The size of your structure will be the same or larger than the size of the unsigned int

If you define

bit eightBits[8]; 

It will not define the array of bits only the array of structures. It will have the size of 8*sizeof(bit) which will be at least 8*sizeof(unsigned int).

If you want to define an object which can only have the value of 0 or 1, the best way is to use bool type, as bool can only have value 0 or 1 despite the assigned value

#include <stdio.h>
#include <stdbool.h>

int main(void)
{
    bool x = 1;
    printf("%d\n", x);
    x = 100;
    printf("%d\n", x);
    x = -100;
    printf("%d\n", x);
    x = 0;
    printf("%d\n", x);
}

will output

1
1
1
0

Upvotes: 4

Related Questions