C++ 位偏移实现bitmap
#pragma once
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
using namespace std;
#define BM_Max 8000000000
class BitMap
{
public:
BitMap(unsigned);
~BitMap(void);
bool getBit(unsigned);
void setBit(unsigned);
void resetBit(unsigned);
private:
unsigned size;
char* pointer;
};
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
using namespace std;
#define BM_Max 8000000000
class BitMap
{
public:
BitMap(unsigned);
~BitMap(void);
bool getBit(unsigned);
void setBit(unsigned);
void resetBit(unsigned);
private:
unsigned size;
char* pointer;
};
#include "BitMap.h"
BitMap::BitMap(unsigned size)
{
if(size < BM_Max)
{
this->size = size;
unsigned byteNum = size/8 + 1;
this->pointer = (char*)malloc(sizeof(int)*byteNum);
for(unsigned i = 0; i < byteNum; i++){
*(pointer+i) = 0;
}
}
else
{
cout << "Error! Over the max size of Bit map.\n";
exit(-1);
}
}
BitMap::~BitMap(void)
{
if(pointer != NULL){
free(this->pointer);
}
}
bool BitMap::getBit(unsigned pos)
{
unsigned numOfchar = pos/(sizeof(char)*8);
int restOfchar = pos%8;
char tmp = *(this->pointer + numOfchar);
return (tmp & (1 << restOfchar));
}
void BitMap::setBit(unsigned pos)
{
unsigned numberOfchar = pos/(sizeof(char)*8);
int restOfchar = pos%8;
char tmp = *(this->pointer + numberOfchar);
tmp |= 1 << restOfchar;
*(this->pointer + numberOfchar) = tmp;
}
void BitMap::resetBit(unsigned pos)
{
unsigned numberOfchar = pos/(sizeof(char)*8);
int restOfchar = pos%8;
char tmp = *(this->pointer + numberOfchar);
tmp &= ~(1 << restOfchar);
*(this->pointer + numberOfchar) = tmp;
}
BitMap::BitMap(unsigned size)
{
if(size < BM_Max)
{
this->size = size;
unsigned byteNum = size/8 + 1;
this->pointer = (char*)malloc(sizeof(int)*byteNum);
for(unsigned i = 0; i < byteNum; i++){
*(pointer+i) = 0;
}
}
else
{
cout << "Error! Over the max size of Bit map.\n";
exit(-1);
}
}
BitMap::~BitMap(void)
{
if(pointer != NULL){
free(this->pointer);
}
}
bool BitMap::getBit(unsigned pos)
{
unsigned numOfchar = pos/(sizeof(char)*8);
int restOfchar = pos%8;
char tmp = *(this->pointer + numOfchar);
return (tmp & (1 << restOfchar));
}
void BitMap::setBit(unsigned pos)
{
unsigned numberOfchar = pos/(sizeof(char)*8);
int restOfchar = pos%8;
char tmp = *(this->pointer + numberOfchar);
tmp |= 1 << restOfchar;
*(this->pointer + numberOfchar) = tmp;
}
void BitMap::resetBit(unsigned pos)
{
unsigned numberOfchar = pos/(sizeof(char)*8);
int restOfchar = pos%8;
char tmp = *(this->pointer + numberOfchar);
tmp &= ~(1 << restOfchar);
*(this->pointer + numberOfchar) = tmp;
}

浙公网安备 33010602011771号