如果没有定义过 byte_t 类型:
#include <stdint.h>
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<uint32_t*>(data)[x] = value; } else if(bits == 24){ mask = 0x00FFFFFF; data += x*3; uint32_t* p = reinterpret_cast<uint32_t*>(data); *p &= ~mask; value &= mask; *p |= value; } else if(bits == 16){ reinterpret_cast<uint16_t*>(data)[x] = value; } else if(bits == 8){ data[x] = value; } else if(bits < 8){ mask = (1<<bits)-1; x *= bits; data += x/8; value &= mask; x &= 7; value <<= x; mask <<= x; mask = ~mask; byte_t n = data[0]; n &= mask; n |= value; data[0] = n; } return 0; }
// 位读取函数 uint32_t bit_get(const byte_t* data, int x, int bits) { uint32_t mask; if(bits == 32){ return reinterpret_cast<const uint32_t*>(data)[x]; } else if(bits == 24){ mask = 0x00FFFFFF; data += x*3; const uint32_t* p = reinterpret_cast<const uint32_t*>(data); return *p & mask; } else if(bits == 16){ return reinterpret_cast<const uint16_t*>(data)[x]; } else if(bits == 8){ return data[x]; } else if(bits < 8){ mask = (1<<bits)-1; x *= bits; data += x/8; x &= 7; return (data[0]>>x) & mask; } }
这个 bitset<> 是 c++ bitset 的扩展版,支持任意长度的数据:
template<std::size_t BITSIZE> 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]; };
文章发布于 2017-02-04 07:26:45 CSDN,现转博客园。
sdragonx https://github.com/sdragonx