标签:
#include <stdio.h> #include <limits.h> #include <string.h> unsigned character_offset(unsigned bit_number); unsigned bit_offset(unsigned bit_number); /** * 将位集合中指定的位设置为0 */ void set_bit(char bit_array[], unsigned bit_number) { bit_array[character_offset(bit_number)] |= 1 << bit_offset(bit_number); } void clear_bit(char bit_array[], unsigned bit_number) { bit_array[character_offset(bit_number)] &= ~(1 << bit_offset(bit_number)); } void assign_bit(char bit_array[], unsigned bit_number, int value){ if(value != 0){ set_bit(bit_array, bit_number); }else{ clear_bit(bit_array, bit_number); } } int test_bit(char bit_array[], unsigned bit_number) { return ( bit_array[character_offset(bit_number)] & 1 << bit_offset(bit_number) ) != 0; } unsigned character_offset(unsigned bit_number) { return bit_number / CHAR_BIT; } unsigned bit_offset(unsigned bit_number) { return bit_number % CHAR_BIT; } int main() { char bit_array[10]; memset(bit_array, 0, 10); set_bit(bit_array, 2); if(test_bit(bit_array, 2)){ printf("2-ok\n"); } if(test_bit(bit_array, 3)){ printf("3-ok\n"); } }
标签:
原文地址:http://www.cnblogs.com/bai-jimmy/p/5205728.html