0
0
0
1. 云栖社区>
2. 博客>
3. 正文

## 大数据处理时的一种BitMap小算法

```char BitMask[] = {0x80 , 0x40 , 0x20 , 0x10 , 0x8 , 0x4 , 0x2 , 0x1};

int WriteNumberBitToByte(char *ByteArra , unsigned int ByteArraSize , int Number)
{
//printf("%d,%d,%d\n",(ByteArraSize * 4) - 1,-(ByteArraSize*4),Number);

if (((int)(ByteArraSize * 4) - 1) < Number || Number<-(int)(ByteArraSize*4) )
{
return 0;	//failed,number out of bytearra.
}

int BaseArraBitPos = ByteArraSize *4;	//ByteArraSize *8 /2

BaseArraBitPos+=Number;

printf("BaseArraBitPos=%d,Number=%d\n",BaseArraBitPos,Number);

return 1;	//success
}

int IsNumberBitInByte(char *ByteArra , unsigned int ByteArraSize , int Number)
{
if (((int)(ByteArraSize * 4) - 1) < Number || Number<-(int)(ByteArraSize*4) )
{
return 0;	//failed,number out of bytearra.
}

int BaseArraBitPos = ByteArraSize *4;	//ByteArraSize *8 /2

BaseArraBitPos+=Number;

return 1;
}

}

void PrintOrderedBitMap(char *BitMap,unsigned int BitMapCount)
{
int MinmumNumber = -(BitMapCount*8/2);
int MaximumValue = (BitMapCount*8/2)-1;

for (int i = MinmumNumber; i <= MaximumValue; ++i)
{
if (IsNumberBitInByte(BitMap,BitMapCount,i))
{
printf("%d,", i);
}
}

printf("\n");
}

int main()
{
int Arra[] = {3,-4,2,0,-1,-8,7,-12,10};

int MaximumValue =Arra[0],MinmumValue=Arra[0];
for (int i = 0; i < sizeof(Arra)/sizeof(Arra[0]); ++i)
{
if(MaximumValue<Arra[i]) {
MaximumValue = Arra[i];
}
if (MinmumValue>Arra[i])
{
MinmumValue = Arra[i];
}
}

MaximumValue=MaximumValue<0?-MaximumValue:MaximumValue;
MinmumValue=MinmumValue<0?-MinmumValue:MinmumValue;

MaximumValue=MaximumValue>MinmumValue?MaximumValue:MinmumValue;

printf("MaximumValue=%d\n",MaximumValue);
//unsigned int BitMapCount = (MaximumValue*2+7)/8;
unsigned int BitMapCount = (MaximumValue+3)/4;
BitMapCount = BitMapCount>0?BitMapCount:1;
char *BitMap = (char*)malloc(BitMapCount);

for (int i = 0; i < sizeof(Arra)/sizeof(Arra[0]); ++i)
{
WriteNumberBitToByte(BitMap,BitMapCount,Arra[i]);
}

PrintOrderedBitMap(BitMap,BitMapCount);
}```

```char BitMask[] = {0x80 , 0x40 , 0x20 , 0x10 , 0x8 , 0x4 , 0x2 , 0x1};

int WriteNumberBitToByte(char *ByteArra , unsigned int ByteArraSize , unsigned int Number)
{
if (((ByteArraSize * 8) - 1) < Number )
{
return 0;	//failed,number out of bytearra.
}

int BytePos = Number / 8;
int BitPos = Number % 8;

return 1;	//success
}

int IsNumberBitInByte(char *ByteArra , unsigned int ByteArraSize , unsigned int Number)
{
if ((ByteArraSize * 8 - 1) < Number )
{
return 0;	//failed,number out of bytearra.
}

int BytePos = Number / 8;
int BitPos = Number % 8;

return 1;
}

}```

+ 关注