Friday, September 4, 2009

BITWRITE BY BITSTREAM

c LANGUAGE STANDARD library contains function to operate on files(fopen ,fclose,fread , fwrite). However there is no function to read/write the data in bit level.The problem is to implement a part of Bitstream involving only readind of the data from a buffer in the bit-level.However the problem defintion has been simplified to aid the completion of the program within the limited amount of time.


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


typedef unsigned char BITSTREAM;


BITSTREAM * bs_open(unsigned char *buf,char *mode)
{
BITSTREAM * bfp;
if(*mode=='r')
{

bfp= buf;
}
else
{
unsigned char buff[10];
bfp=buff;
}
return bfp;
}




BITSTREAM * bs_write(unsigned long val,int bitcnt, BITSTREAM *bfp)
{
int bitrem =0;
static unsigned long bitOffset=0;

static unsigned char buff[10];
int bitfrom2nd;
int value1=0;

int value2=0;
bitrem=8-(bitOffset % 8);

int pos=bitOffset / 8;
//bfp+=pos;
/*increase offset for next call*/

bitOffset+=bitcnt;
if(bitrem >= bitcnt)
{

if(bitrem == 8)
{
value1= 0x00;
}
else
{
value1=buff[pos];
}

value2= (unsigned char)(val<<(8- bitcnt)) >> (8- bitrem);

buff[pos]=value1 | value2;


bfp[pos]=(unsigned char) buff[pos];
}
else
{

value1= buff[pos];


value2= (unsigned char)((val << (8-bitcnt)) >> (8- bitrem) ) ;
buff[pos]= value1 | value2;
bfp[pos]=(unsigned char) buff[pos];



bitfrom2nd = 8-(bitOffset % 8);

if (bitfrom2nd != 0)
{
pos++;
//bfp++;

buff[pos]=(unsigned char)(val << bitfrom2nd);

bfp[pos]=(unsigned char) (&buff[pos]);
}
}

printf(" value1= %d value2= %d bitcount =%d ", value1,value2,bitcnt );

printf(" buff %s %d\t ",buff,bfp);

printf(" bfp %s \n",bfp);


return (bfp);
}


void main()
{
unsigned char buf[10]={'\n'};

BITSTREAM *bfp;


/*clrscr();*/
bfp=bs_open(buf,"w");

bs_write(0x4,4,bfp);
bs_write(0x14,8,bfp);
bs_write(0x9,6,bfp);
bs_write(0x0,3,bfp);
bs_write(0x6,4,bfp);
bs_write(0x44,7,bfp);
bs_write(69,8,bfp);
bs_write(0x4,4,bfp);
bs_write(0x5,4,bfp);
for(int i=0;i<6;i++)
buf[i]=bfp[i];
printf("\nmain buff %s %s\t \n",buf, &bfp);



/*getch();*/
}



output:

C:\TC\karthi>bitwrite
value1= 0 value2= 64 bitcount =4 buff @ 38076048 bfp @\
value1= 64 value2= 1 bitcount =8 buff A@ 38076048 bfp A☺
value1= 64 value2= 2 bitcount =6 buff AB@ 38076048 bfp AB☻a,U?|☻
value1= 64 value2= 0 bitcount =3 buff AB@ 38076048 bfp AB@a,U?|☻
value1= 64 value2= 3 bitcount =4 buff ABC 38076048 bfp ABC♥,U?|♥
value1= 0 value2= 68 bitcount =7 buff ABCD 38076048 bfp ABCD,U?|♥
value1= 0 value2= 69 bitcount =8 buff ABCDE 38076048 bfp ABCDEU?|♦

value1= 0 value2= 64 bitcount =4 buff ABCDE@ 38076048 bfp ABCDE@?|♣

value1= 64 value2= 5 bitcount =4 buff ABCDEE 38076048 bfp ABCDEE?|♣


main buff ABCDEE ABCDEE

No comments:

Post a Comment