C Program to Implement Bit Array

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.

  1. #include <stdio.h>
  2.  
  3. #define SIZE (58) /* amount of bits */
  4. #define ARRAY_SIZE(x) (x/8+(!!(x%8)))
  5.  
  6. char get_bit(char *array, int index);
  7. void toggle_bit(char *array, int index);
  8. void toggle_bit(char *array, int index) {
  9.     array[index / 8] ^= 1 << (index % 8);
  10. }
  11.  
  12. char get_bit(char *array, int index) {
  13.     return 1 & (array[index / 8] >> (index % 8));
  14. }
  15. int main(void) {
  16.     /* initialize empty array with the right size */
  17.     char x[ARRAY_SIZE(SIZE)] = { 0 };
  18.     int i;
  19.  
  20.     for (i = 0; i < SIZE; i += 2)
  21.         toggle_bit(x, i);
  22.     toggle_bit(x, 56);
  23.     for (i = 0; i < SIZE; i++)
  24.         printf("%d: %d\n", i, get_bit(x, i));
  25.  
  26.     return 0;
  27. }

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

Here’s the list of Best Books in C Programming, Data Structures and Algorithms.

advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
I’m Manish - Founder and CTO at Sanfoundry. I’ve been working in tech for over 25 years, with deep focus on Linux kernel, SAN technologies, Advanced C, Full Stack and Scalable website designs.

You can connect with me on LinkedIn, watch my Youtube Masterclasses, or join my Telegram tech discussions.

If you’re in your 20s–40s and exploring new directions in your career, I also offer mentoring. Learn more here.