在linux C中寻找位图实现API

时间:2013-06-05 18:43:33

标签: c linux api bitmap

我想在linux C中使用位图API。

我需要2 ^ 18位,所以需要32KB内存。我会经常在位图中设置和取消设置位。

基本上我需要API,如:

set_bitmap(int i)  // it sets the i-th bit to 1 in the bitmap
unset_bitmap(int i) // it sets the i-th bit to 0 in the bitmap
bitmap_t create_bitmap(int n) // it creates a bitmap of size n, like n=2^18

是否有任何源代码或类似的源代码?

谢谢!

3 个答案:

答案 0 :(得分:8)

这并不难。

typedef unsigned char* bitmap_t;

void set_bitmap(bitmap_t b, int i) {
    b[i / 8] |= 1 << (i & 7);
}

void unset_bitmap(bitmap_t b, int i) {
    b[i / 8] &= ~(1 << (i & 7));
}

void get_bitmap(bitmap_t b, int i) {
    return b[i / 8] & (1 << (i & 7)) ? 1 : 0;
}

bitmap_t create_bitmap(int n) {
    return malloc((n + 7) / 8);
}

答案 1 :(得分:1)

功能get_bitmap中的其他答案似乎有误。位检测应该像这样:

b[i / 8] & (1 << (i & 7))

然后整个纠正的代码是:

typedef unsigned char* bitmap_t;

void set_bitmap(bitmap_t b, int i) {
    b[i / 8] |= 1 << (i & 7);
}

void unset_bitmap(bitmap_t b, int i) {
    b[i / 8] &= ~(1 << (i & 7));
}

int get_bitmap(bitmap_t b, int i) {
    return b[i / 8] & (1 << (i & 7)) ? 1 : 0;
}

bitmap_t create_bitmap(int n) {
    return malloc((n + 7) / 8);
}

答案 2 :(得分:1)

// C++ API
//
#include <iostream>
#include <assert.h>

using namespace std;

class BitSet
{
    public:
        BitSet(int n); 
        ~BitSet();
        bool setBit(int index);
        bool unsetBit(int index);
        char getBit(int index);
        void printBits();

    private:
        unsigned char* m_buffer;
        int m_range;
};

BitSet::BitSet(int n)
{
    m_buffer = (unsigned char*) malloc((n+7)/8);
    assert(m_buffer);
    for (int ii = 0; ii < n; ii++) {
        m_buffer[ii] = 0x00;
    }   
    m_range = n;
}

BitSet::~BitSet()
{
    if (m_buffer) {
        free(m_buffer);
    }   
}

bool
BitSet::setBit(int index)
{
    if (index < 0 || index >= m_range) {
        return false;
    }   

    m_buffer[index/8] = m_buffer[index/8] | ((0x01 << (index%8)));
    return true;
}

bool
BitSet::unsetBit(int index)
{
    if (index < 0 || index >= m_range) {
        return false;
    }   

    m_buffer[index/8] &= ~(0x01 << (index%8));
    return true;
}

char
BitSet::getBit(int index)
{
    if (index < 0 || index >= m_range) {
        return false;
    }

    return (m_buffer[index/8] & (0x01 << (index%8))) ? 0x01 : 0x00;
}

void
BitSet::printBits()
{
    for (int ii = 0; ii < m_range/8; ii++) {
        cout<<"'"<<std::hex<<int(m_buffer[ii])<<"'";
    }
    cout<<endl;
}