This is a C Program to implement Bit Array. A bit array is an array data structure that compactly stores bits. It can be used to implement a simple set data structure. A bit array is effective at exploiting bit-level parallelism in hardware to perform operations quickly.
A typical bit array stores bt bits, where t is the number of bits in the unit of storage, such as a byte or word, and b is some non-negative integer. If t does not divide the number of bits to be stored, some space is wasted due to internal fragmentation.
Here is source code of the C Program to Implement Bit Array. The C program is successfully compiled and run on a Linux system. The program output is also shown below.
#include <stdio.h>
#define SIZE (58) /* amount of bits */
#define ARRAY_SIZE(x) (x/8+(!!(x%8)))
char get_bit(char *array, int index);
void toggle_bit(char *array, int index);
void toggle_bit(char *array, int index) {
array[index / 8] ^= 1 << (index % 8);
}
char get_bit(char *array, int index) {
return 1 & (array[index / 8] >> (index % 8));
}
int main(void) {
/* initialize empty array with the right size */
char x[ARRAY_SIZE(SIZE)] = { 0 };
int i;
for (i = 0; i < SIZE; i += 2)
toggle_bit(x, i);
toggle_bit(x, 56);
for (i = 0; i < SIZE; i++)
printf("%d: %d\n", i, get_bit(x, i));
return 0;
}
Output:
$ gcc BitArray.c $ ./a.out 0: 1 1: 0 2: 1 3: 0 4: 1 5: 0 6: 1 7: 0 8: 1 9: 0 10: 1 11: 0 12: 1 13: 0 14: 1 15: 0 16: 1 17: 0 18: 1 19: 0 20: 1 21: 0 22: 1 23: 0 24: 1 25: 0 26: 1 27: 0 28: 1 29: 0 30: 1 31: 0 32: 1 33: 0 34: 1 35: 0 36: 1 37: 0 38: 1 39: 0 40: 1 41: 0 42: 1 43: 0 44: 1 45: 0 46: 1 47: 0 48: 1 49: 0 50: 1 51: 0 52: 1 53: 0 54: 1 55: 0 56: 0 57: 0
Sanfoundry Global Education & Learning Series – 1000 C Programs.
advertisement
advertisement
Here’s the list of Best Books in C Programming, Data Structures and Algorithms.
Related Posts:
- Check Computer Science Books
- Watch Advanced C Programming Videos
- Practice Computer Science MCQs
- Apply for C Internship
- Check C Books