c语言实现bitmap的基本操作

 1 /**
 2  *文件:bit.h
 3  *目的: 实现bitmap数据结构
 4  *作者:杜小波
 5  *联系方式:code2living@gmail.com
 6  **/
 7 
 8 #ifndef _BIT_H_
 9 #define _BIT_H_
10 
11 /**
12  *存储bitmap的结构体
13  *存储的顺序从左至右
14  **/
15 struct _Bits;
16 typedef struct _Bits *bits;
17 
18 /**
19  *获得bitmap
20  *@length bitmap的长度
21  *@return 所有位都初始化为0的bitmap
22  */
23 bits bit_new(unsigned int length);
24 
25 /**
26  *销毁一个bitmap
27  **/
28 void bit_destroy(bits bit);
29 
30 /**
31  *获得y一个bitmap的长度
32  *@bit 需要获得长度的bitmap
33  *@return bit的长度
34  **/
35 unsigned int bit_length(bits bit);
36 
37 /**
38  *设置bitmap中相应位置的值
39  *@bit 待设置的bitmap
40  *@pos  需要设置的位置
41  **/
42 void bit_set(bits bit, unsigned int pos, unsigned char value);
43 
44 /**
45  *设置bitmap中相应位置的值
46  *@bit  待获取的bitmap
47  *@pos  获取的位置
48  **/
49 char bit_get(bits bit, unsigned int pos);
50 
51 #endif /*_BITS_H_*/
#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;
}
 1 #include <stdio.h>
 2 #include "bit.h"
 3 #define LEN 15
 4 int main(void)
 5 {
 6     bits bit = bit_new(LEN);
 7 
 8     printf("length: %u\n", bit_length(bit));
 9 
10     unsigned int test_value = 0x735D;
11     unsigned char value;
12     int i;
13     for (i = LEN - 1; i >= 0; i--) {
14         value = test_value & 1;
15         bit_set(bit, i, value);
16         test_value >>= 1;
17     }
18 
19     for (i = 0; i < LEN; i++) {
20         printf("%d", bit_get(bit, i));
21     }
22     printf("\n");
23 
24     bit_destroy(bit);
25 
26     return 0;
27 }

欢迎大家对小弟的作品进行挑错

原文地址:https://www.cnblogs.com/chunxia/p/3049243.html