任意数据长度的bitset,以及按位读写数据的函数

 如果没有定义过byte_t类型:

#include
typedef uint8_t byte_t;
//typedef unsigned char byte_t; //1个byte字节,8位,一般系统中能表示的最小字节数据。

uint32_t bit_set(byte_t* data, size_t x, size_t bits, uint32_t value)
{
    uint32_t mask;
    if(bits == 32){
        reinterpret_cast(data)[x] = value;
    }
    else if(bits == 24){
        mask = 0x00FFFFFF;
        data += x*3;
        uint32_t* p = reinterpret_cast(data);
        *p &= ~mask;
        value &= mask;
        *p |= value;
    }
    else if(bits == 16){
        reinterpret_cast(data)[x] = value;
    }
    else if(bits == 8){
        data[x] = value;
    }
    else if(bits < 8){
        mask = (1<

 

uint32_t bit_get(const byte_t* data, int x, int bits)
{
    uint32_t mask;
    if(bits == 32){
        return reinterpret_cast(data)[x];
    }
    else if(bits == 24){
        mask = 0x00FFFFFF;
        data += x*3;
        const uint32_t* p = reinterpret_cast(data);
        return *p & mask;
    }
    else if(bits == 16){
        return reinterpret_cast(data)[x];
    }
    else if(bits == 8){
        return data[x];
    }
    else if(bits < 8){
        mask = (1<>x) & mask;
    }
}

这个bitset<>是c++bitset的扩展版,支持任意长度的数据

template
struct bitset
{
public:
    const static std::size_t byte_size = BITSIZE/8 + (BITSIZE&0x07 ? 1 : 0);
public:
    bitset()
    {
    	this->reset();
    }

    size_t size()const
    {
    	return BITSIZE;
    }

    bool bit(size_t id)const
    {
        return (data[id/8]>>(id&0x07))&0x01;
    };
    bool operator[](size_t id)const
    {
    	return this->bit(id);
    }

    void set()
    {
    	memset(data, 0xFF, byte_size);
    }
    bool set(size_t id)
    {
    	byte_t& b = data[id/8];
        b |= 1<<(id&0x07);
        return true;
    }
    void reset()
    {
    	memset(data, 0, byte_size);
    }
    bool reset(size_t id)
    {
    	byte_t& b = data[id/8];
       	b &= ~(1<<(id&0x07));
        return false;
    }
public:
	byte_t data[byte_size];
};

 

 

 

你可能感兴趣的:(c++)