码迷,mamicode.com
首页 > 其他好文 > 详细

位集合

时间:2016-02-21 22:43:47      阅读:214      评论:0      收藏:0      [点我收藏+]

标签:

#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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!