90 lines
2.5 KiB
C
90 lines
2.5 KiB
C
/**
|
|
* 日期: 2025-03-08
|
|
* 作者: coffee
|
|
* 描述: 比特数组, 支持多字节
|
|
* 定义上使用宏 HBIT_DEFINE 定义变量名
|
|
* 支持超长比特, 默认支持255比特, 需要更高需定义HBIT_LEN_USE16 或 HBIT_LEN_USE32
|
|
*/
|
|
|
|
|
|
#ifndef __H_BIT__
|
|
#define __H_BIT__
|
|
|
|
|
|
#include <stdint.h>
|
|
|
|
typedef uint8_t HBitType;
|
|
|
|
#ifdef HBIT_LEN_USE32
|
|
typedef uint32_t HBitLenType;
|
|
typedef uint32_t HBitIndexType;
|
|
#elif defined(HBIT_LEN_USE16)
|
|
typedef uint16_t HBitLenType;
|
|
typedef uint16_t HBitIndexType;
|
|
#else
|
|
typedef uint8_t HBitLenType;
|
|
typedef uint8_t HBitIndexType;
|
|
#endif
|
|
|
|
/** ============================================================================================= **/
|
|
|
|
// 开头带_的宏都是内部辅助宏, 不需要直接调用
|
|
|
|
enum eHBitFlag {
|
|
|
|
kHBitInitFlag = 0x80,
|
|
};
|
|
|
|
#pragma pack(1)
|
|
typedef struct _HBitBase {
|
|
uint8_t flag;
|
|
HBitLenType len;
|
|
uint8_t data[0];
|
|
} _HBitBase;
|
|
#pragma pack()
|
|
|
|
#define _HBIT_CALC_LEN(num) (sizeof(_HBitBase) + (((num) + 7) / 8))
|
|
|
|
#ifdef HBIT_LEN_USE32
|
|
#define _HBIT_INIT_SIZE(size) ((size >> 24) & 0xff), ((size >> 16) & 0xff), ((size >> 8) & 0xff), (size & 0xff)
|
|
#define _HBIT_INIT_SIZE_INIT(size) ((size[0] << 24) | (size[1] << 16) | (size[2] << 8) | (size[3] & 0xff))
|
|
#elif defined(HBIT_LEN_USE16)
|
|
#define _HBIT_INIT_SIZE(size) ((size >> 8) & 0xff), (size & 0xff)
|
|
#define _HBIT_INIT_SIZE_INIT(size) ((size[0] << 8) | (size[1] & 0xff))
|
|
#else
|
|
#define _HBIT_INIT_SIZE(size) (size & 0xff)
|
|
#define _HBIT_INIT_SIZE_INIT(size) (size[0] & 0xff)
|
|
#endif
|
|
|
|
/** ============================================================================================= **/
|
|
|
|
// 定义HBit变量, name为变量名, num为需要比特长度
|
|
#define HBIT_DEFINE(name, num) HBitType name[_HBIT_CALC_LEN(num)] = { kHBitInitFlag, _HBIT_INIT_SIZE(num), 0 }
|
|
|
|
// 声明HBit变量
|
|
#define HBIT_EXTERN(name, num) extern HBitType name[_HBIT_CALC_LEN(num)]
|
|
|
|
// 设置比特值
|
|
void HBitSet(HBitType *data, HBitIndexType index, HBitType value);
|
|
|
|
// 获取比特值
|
|
HBitType HBitGet(const HBitType *data, HBitIndexType index);
|
|
|
|
// 填充比特值
|
|
void HBitFill(HBitType *data, HBitType value);
|
|
|
|
// 取反指定位的比特值
|
|
void HBitReverse(HBitType *data, HBitIndexType index);
|
|
|
|
// 如果存在任意比特为1, 返回1, 否则返回0
|
|
HBitType HBitAny(const HBitType *data);
|
|
|
|
// 如果所有比特为1, 返回1, 否则返回0
|
|
HBitType HBitAll(const HBitType *data);
|
|
|
|
// 如果所有比特为0, 返回1, 否则返回0
|
|
HBitType HBitNone(const HBitType *data);
|
|
|
|
|
|
#endif //__H_BIT__
|