0

Using structure a character variable is declared. I want to access(read and write) all the bit of that character type variable. I have solved that in my way using Bit Field. The code is given below. But if i want to print them they should be called individually. I am unable to call them in a loop.

#include<stdio.h>
struct SevenSegmentValue
{
  unsigned char bit0:1;
  unsigned char bit1:1;
  unsigned char bit2:1;
};

struct SevenSegmentValue abc[3]={{1,0,1},{0,1,1},{1,1,0}};

int main(void)
{
    printf( "Memory size occupied by status1 : %d\n", sizeof(abc));
    printf( "Memory size occupied by status1 : %d\n", abc[2].bit0);
    printf( "Memory size occupied by status1 : %d\n", abc[2].bit1);
    printf( "Memory size occupied by status1 : %d\n", abc[2].bit2);
}
klutt
  • 30,332
  • 17
  • 55
  • 95

1 Answers1

2

You can't create an array of bit fields, so you can't loop through them.

If you want to print all the bit in an unsigned char, you can use bit shifting to access each bit:

unsigned char c = 0x32;
int i;
for (i=0; i<8; i++) {
    printf("bit %d: %d\n", i, ((c >> i) & 1));
}

Output:

bit 0: 0
bit 1: 1
bit 2: 0
bit 3: 0
bit 4: 1
bit 5: 1
bit 6: 0
bit 7: 0

Note that this print the least significant bit first. If you want the most significant bit first, have the loop count down instead of up.

dbush
  • 205,898
  • 23
  • 218
  • 273