how can create bit-field array variable size? following code tried, didn't work.
#include <stdio.h> int main() { int n=4; struct bite{ unsigned a1:2; unsigned a2:2; : : unsigned a(n-1):2; unsigned a(n):2; }bits; for(i=1;i<=n;i++) bits.a[i]=i; for(i=1;i<=n;i++) printf("%d ",bits.a[i]); return 0; }
the members of struct
cannot defined @ runtime.
you simulate bit array using char
array , macros.
#define bitarray(array, bits) \ unsigned char array[bits / 8 + 1] #define setbit(array, n) \ { array[n / 8] |= (1 << (n % 8)) } while (0) #define getbit(array, n) \ ((array[n / 8] >> (n % 8)) & 1) int main(void) { bitarray(bits, 42); /* define 42 bits , init 0s (in fact allocates memory (42/8 + 1) * 8 bits). */ setbit(bits, 2); /* set bit 2. */ int bit2 = getbit(bits, 2); /* bit 2 */ ...
similar 2-bit words per code:
#include <stdlib.h> #include <stdio.h> #include <string.h> #define define2bitwordarray(array, two_bit_words) \ unsigned char array[two_bit_words / 4 + 1] #define set2bitword(array, n, value) \ { array[n / 4] |= (unsigned char)((value & 0x11) << (2 * (n % 4))); } while (0) #define get2bitword(array, n) \ ((array[n / 4] >> (2 * (n % 4))) & 0x11) int main(void) { size_t n = 10; define2bitwordarray(bits, n); /* define 10 two-bits words (in fact allocates memory (10/4 + 1) * 4 two-bit bits). */ memset(bits, 0, sizeof bits); /* set bits 0. */ for(size_t = 0; < n; i++) /* c array's indexes 0-based. */ { set2bitword(bits, i, i); } for(size_t = 0; < n; i++) { printf("%d ", get2bitword(bits, i)); } }
Comments
Post a Comment