c 언어 는 bitmap 의 기본 동작 을 실현 합 니 다.

12635 단어 bitmap
 1 /**

 2  *  :bit.h

 3  *  :   bitmap    

 4  *  :   

 5  *    :[email protected]

 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
", 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("
"); 23 24 bit_destroy(bit); 25 26 return 0; 27 }

동생 의 작품 을 잘못 고 른 것 을 환영 합 니 다.

좋은 웹페이지 즐겨찾기