C和指针 第五章 位数组
5.4的习题:编写一组函数,实现维数组,函数原型如下:
//指定位设置为1
void set_bit(char bit_array[], unsigned bit_number);
//指定位清零 void clear_bit(char bit_array[], unsigned bit_number);
//指定位清零,否则设置为1
void assign_bit(char bit_array[], unsigned bit_number, int value);
//参数指定位置为1返回真,为0返回1 int test_bit(char bit_array[], unsigned bit_number);
每个函数第一位是字符数组,实际存储所有的位,第二位参数用于标示,要访问的位,函数的调用者要防止这个值过大,超过数组边界。
//字符偏移 unsigned int char_offset(unsigned bit_number) { return bit_number / CHAR_BIT; } //bit位偏移 unsigned int bit_offset(unsigned bit_number) { return bit_number % CHAR_BIT; } void set_bit(char bit_array[], unsigned bit_number) { bit_array[char_offset(bit_number)] |= 1 << bit_offset(bit_number); } void clear_bit(char bit_array[], unsigned bit_number) { bit_array[char_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) { //对该bit位进行与操作,如果是1则结果还是 1<< (bit_number % CHAR_BIT) unsigned isZero = bit_array[bit_number / CHAR_BIT] & (1 << (bit_number % CHAR_BIT)); if (isZero == (1 << (bit_number % CHAR_BIT))) { return TRUE; } return FALSE; }