数值类型连续Bit存储读取方法
一般为了节省内存,一个unsigned char占8bit,分bit进行存储。存储时单个bit对外可以使用bool值,多个连续的bit可以使用unsigned char。
获取/设置单个bit值方法
获取/设置多个连续bit值方法
static bool getBitValue(unsigned char data, unsigned char bit) { return (data >> bit) & 1; } static void setBitValue(unsigned char &data, bool value, unsigned char bit) { if(value) { data |= (1u << bit); } else { data &= ~(1u << bit); } } static unsigned char getRangeBitValue(unsigned char data, unsigned char lower_bit, unsigned char high_bit) { data = data & ((1 << (high_bit + 1)) - 1); data = data >> lower_bit; return data; } static void setRangeBitValue(unsigned char &data,unisgned char value, unisgned char lower_bit, unsigned char high_bit) { value = value << lower_bit; unsigned char mask = (1 << (high_bit + 1)) -1; mask = mask & ~((1 << lower_bit) - 1); value &= mask; data &= ~mask; data |= value; }