bit.h
#ifndef _BIT_H_
#define _BIT_H_
/**
*存储bitmap的结构体
*存储的顺序从左至右
**/
struct _Bits;
typedef struct _Bits *bits;
/**
*获得bitmap
*@length bitmap的长度
*@return 所有位都初始化为0的bitmap
*/
bits bit_new(unsigned int length);
/**
*销毁一个bitmap
**/
void bit_destroy(bits bit);
/**
*获得y一个bitmap的长度
*@bit 需要获得长度的bitmap
*@return bit的长度
**/
unsigned int bit_length(bits bit);
/**
*设置bitmap中相应位置的值
*@bit 待设置的bitmap
*@pos 需要设置的位置
**/
void bit_set(bits bit, unsigned int pos, unsigned char value);
/**
*设置bitmap中相应位置的值
*@bit 待获取的bitmap
*@pos 获取的位置
**/
char bit_get(bits bit, unsigned int pos);
#endif /*_BITS_H_*/
bit.c
#include "bit.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct _Bits {
char *bits;
unsigned int length;
};
bits bit_new(unsigned int length)
{
bits new_bits = (bits)malloc(sizeof(struct _Bits));
if (new_bits == NULL)
return NULL;
int char_nums = sizeof(char) * (length >> 3) + 1;
new_bits->bits = (char *)malloc(char_nums);
if (new_bits == NULL) {
free(new_bits);
return NULL;
}
memset(new_bits->bits, 0, char_nums);
new_bits->length = length;
return new_bits;
}
void bit_destroy(bits bit)
{
free(bit->bits);
free(bit);
}
unsigned int bit_length(bits bit)
{
return bit->length;
}
void bit_set(bits bit, unsigned int pos, unsigned char value)
{
unsigned char mask = 0x80 >> (pos & 0x7);
if (value) {
bit->bits[pos>>3] |= mask;
} else {
bit->bits[pos>>3] &= ~mask;
}
}
char bit_get(bits bit, unsigned int pos)
{
unsigned char mask = 0x80 >> (pos & 0x7);
return (mask & bit->bits[pos>>3]) == mask ? 1 : 0;
}
main.c
#include <stdio.h>
#include "bit.h"
#define LEN 15
int main(void)
{
bits bit = bit_new(LEN);
printf("length: %u\n", bit_length(bit));
unsigned int test_value = 0x735D;
unsigned char value;
int i;
for (i = LEN - 1; i >= 0; i--) {
value = test_value & 1;
bit_set(bit, i, value);
test_value >>= 1;
}
for (i = 0; i < LEN; i++) {
printf("%d", bit_get(bit, i));
}
printf("\n");
bit_destroy(bit);
return 0;
}