2009年4月7日 星期二

知識+ 大陣列中bit處理(可跨byte)


//===================================================================
// 20090331 知識 +
// http://tw.knowledge.yahoo.com/question/question?qid=1509033101375
// 發問者 : http://tw.knowledge.yahoo.com/my/my?show=AE03178958
//===================================================================

#include <stdio.h>
#include <stdlib.h>

#pragma pack(1)
struct BYTE
{
unsigned char Byte;
unsigned int getBits(unsigned int i, unsigned char l=1 )
{
unsigned int rtn = 0;
if (l>32l==0) return 0;
int n=i/8;
int b=i%8;
unsigned char * p = (unsigned char *)((&Byte)+n);
while(l-->0)
{
rtn = ((unsigned int)(((*p)>>(7-b))&1))<<l;
if (++b==8){ b=0; p++;}
}
return rtn;
}
void setBits(unsigned int i,unsigned int d, unsigned char l=1)
{
if (l>32l==0) return;
int n=i/8;
int b=i%8;
unsigned char * p = (unsigned char *)((&Byte)+n);
while(l-->0)
{
if ((d>>l)&1) *p = 0x80>>b;
else *p &= ~(0x80>>b);
if (++b==8){ b=0; p++;}
}
}
};

int main()
{
BYTE a[32];

printf( "\n a[] size = %d, BYTE size= %d\n", sizeof(a), sizeof(BYTE));
for(int i=0; i<30; i++)
a[i].Byte=0;

for(int i=0; i<240; i++)
a[0].setBits(i,(i%3==0)?1:0);

printf ("\nDump Buffer:\n");
for(int i=0; i<30; i++)
printf("0x%02X%c",a[i].Byte, (i%10==9)? '\n': ' ');

//
printf ("\nSet & Get:");
for(int i=0; i<240; i+=3)
{
a[0].setBits(i, (i/3%8), 3);
printf("%cx%01X", (i%60==0)? '\n': ' ', a[0].getBits(i,3) );
}

printf ("\n\nDump Buffer:\n");
for(int i=0; i<30; i++)
printf("0x%02X%c",a[i].Byte, (i%10==9)? '\n': ' ');
return 0;
}

//=============================================================================

沒有留言:

張貼留言