版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/HQ354974212/article/details/84566043
我们知道,unsigned char 是8位,可以存储数据的值是 0-255 , 一共256个值。
下面可以自己设计一种数据结构,用于存储40位的数据类型,当然这里的40 (8 *5 )你可以随意扩展,比如 256位 = 8 *32
话不多说,看下面的示例代码:
#include <iostream>
typedef unsigned char BYTE;
#define CountArray(Array) (sizeof(Array)/sizeof(Array[0]))
struct Bit40 // 40位结构
{
BYTE Value[5] = {0}; // //BYTE 8 位 * 5 = 40
};
struct Bit40Handle
{
static void Clear(Bit40& p)
{
for (int i = 0; i < CountArray(p.Value); ++i)
p.Value[i] = 0;
}
static void SetValue(Bit40& p, BYTE pArray[], BYTE Size)
{
//将数据设置到里面去
for (int i = 0; i < Size && i < CountArray(p.Value); ++i)
{
p.Value[i] = pArray[i];
}
}
static void SetBitStates(Bit40& p, BYTE BitIndex, bool States)
{
BYTE ArrayIndex = static_cast<BYTE>(BitIndex / 8);
BYTE ChangeIndex = static_cast<BYTE>(BitIndex % 8);
BYTE BitValue = static_cast<BYTE>(1 << ChangeIndex);
if (States)
p.Value[ArrayIndex] |= BitValue;
else
p.Value[ArrayIndex] ^= BitValue;
}
static bool GetBitStates(Bit40& p, BYTE BitIndex)
{
BYTE ArrayIndex = static_cast<BYTE>(BitIndex / 8);
BYTE ChangeIndex = static_cast<BYTE>(BitIndex % 8);
return ((p.Value[ArrayIndex] & (1 << ChangeIndex)) == (1 << ChangeIndex));
}
static void Print(Bit40 p )
{
std::cout << std::endl;
for (size_t i = 0; i < 40; i++)
{
std::cout<<GetBitStates(p, i);
}
std::cout<< std::endl;
}
};
int main()
{
Bit40 a; // 40个标记位
//索引0位置为1
Bit40Handle::SetBitStates(a, 0, true);
Bit40Handle::Print(a);
//索引39位置为1
Bit40Handle::SetBitStates(a, 39, true);
Bit40Handle::Print(a);
//获取索引位置
std::cout<<"\n第0位的值"<< Bit40Handle::GetBitStates(a, 0);
}
运行效果如下: