zoukankan      html  css  js  c++  java
  • 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;
    }
    

      

  • 相关阅读:
    Android中 requestCode与resultCode的区别与用法
    Activity与Fragment之间的通信
    关于解决 从相册中选择照片后无法剪切图片以及无法加载图片的问题
    Codeforces Round #313 (Div. 2) C. Geralds Hexagon
    HDU 2669 Romantic
    HDU 1405 The Last Practice
    HDU Wolf and Rabbit
    LightOJ 1104 Birthday Paradox
    11181
    Tr A
  • 原文地址:https://www.cnblogs.com/yangxunwu1992/p/5777937.html
Copyright © 2011-2022 走看看