2016년 9월 19일 월요일

간단한 Bit Vector 구현

Programming Pearls 칼럼.1에 소개되는 bit vector를 class로 구현해 보았다.


#include <stdio.h>

class BitVector
{
    private :
        static const int BITSPERWORD = 32; 
        int bitVectorSize;
        int *ptr;

    public :
        BitVector(int size);
        ~BitVector();

        void set(int i); 
        void get(int i); 
};

BitVector::BitVector(int size)
    : bitVectorSize(size), 
      ptr(NULL)
{
    ptr = new int[bitVectorSize/BITSPERWORD + 1](); 
}

BitVector::~BitVector()
{
    delete[] ptr;
}

void BitVector::set(int i)
{
    if( i < 0 || i > bitVectorSize) 
    {   
        printf("invalid..%d, (max : %d)\n", i, bitVectorSize);
        return;
    }   

    if( i <= 0) return;

    printf("input %-5d into the bit vector..\n", i); 

    int tmp = 1;
    tmp = tmp << (i % BITSPERWORD);
    
    ptr[i/BITSPERWORD] |= tmp;
}
void BitVector::get(int i)
{
    if(i < 0 || i > bitVectorSize)
    {
        printf("invalid..(%d)\n", i);
        return;
    }

    int tmp = (i == 0 ? 0 : 1);
    tmp = tmp << (i % BITSPERWORD);

    int pos = ptr[i/BITSPERWORD] & tmp;

    printf("%-5d %s\n", i, pos == 0 ? "off" : "on");
}

int main()
{
    BitVector bv(100);
    bv.set(21);
    bv.set(100);
    bv.set(11);

    bv.get(11);
    bv.get(10);
    bv.get(21);
    bv.get(0);
    bv.get(3);
    bv.get(100);
}

결과

input 21    into the bit vector..
input 100   into the bit vector..
input 11    into the bit vector..
11    on
10    off
21    on
0     off
3     off
100   on

댓글 없음:

댓글 쓰기