c [cpp] /* * ===================================================================================== * * Filename: bitset.c * * Description: * * Version: 1.0 * Created: 02/04/2013 10:25:38 AM * Revision: none * Compiler: gcc * * Author: jiangwenlong (http://blog.csdn.net/chlaws), [email protected] * Company: PIPI * * ===================================================================================== */ #include <stdio.h> #include <stdlib.h> #include <string.h> //find index of array #define BIT_WORD(n) ((n)/32) //get number of bit value #define BIT_MASK(n) (1<<((n)%32)) static int bit_size = 0; #define uint unsigned int static uint *bitset = NULL; //return <0, have error; =0 successful //@param length is bitset have length bits int create_bitset(int length); void free_bitset(); //return < 0, have error; =0 successful //@param nbit is bit index //@param value avalid 0 or 1 int set_bitset(int nbit,int value); //return < 0 have error; =0 succesful //@param nbit is bit index int get_bitset(int nbit); int create_bitset(int length) { int nword = BIT_WORD(length); int need_len = (nword+1)* sizeof(uint); bitset = (uint*)malloc(need_len); if(bitset == NULL) return -1; memset(bitset,0,need_len); bit_size = need_len * 8; return 0; } void free_bitset() { free(bitset); } int set_bitset(int nbit,int value) { if(nbit < 0 || nbit > bit_size) return -1; if(bitset == NULL) return -2; if(value != 0 && value != 1) return -3; int index = BIT_WORD(nbit); if(value == 1) bitset[index] |= BIT_MASK(nbit); else{ bitset[index] &= ~BIT_MASK(nbit); } return 0; } int get_bitset(int nbit) { if(nbit < 0 || nbit > bit_size) return -1; if(bitset == NULL) return -2; int index = BIT_WORD(nbit); return (bitset[index] & BIT_MASK(nbit)) >> (nbit%32); } //test bitset int main() { int n = 4125; create_bitset(n); int i = 0; for(; i < n; ++i){ if(i%2 == 0) set_bitset(i,0); else set_bitset(i,1); } www.2cto.com for(i = 0; i < n; ++i){ printf("bit[%d]=%d ",i,get_bitset(i)); if(i > 0 && i % 10 == 0) printf("\n"); } printf("\n"); free_bitset(); return 0; }