I like programming ie., development. Since my proffessional career started, i am working on C programming only. Thats why always i will be working on C programming. I like to work on Programming.
While working on bit related programming like setting a bit, resetting a bit in an integer, i was getting confusions. Concept and theory will be present in my mind but i will take too much time to produce on paper. Programming on the IDE or any programming tool will be easy. But to write on a paper, me like people feel little difficulty.
Hence i have written some programs and the same i am giving here. This could be helpful to many to understand bits.
1. Program to make a bit 0 if it was 1 and to make 1 if it was 0
void BitToggle()
{
int Data, Bit;
int t1,t2;
printf("Enter the data \n");
scanf("%d",&Data);
printf("Enter the bit number to be toggled\n");
scanf("%d",&Bit);
if((Data >> Bit) & 0x01) //if bit is set
{
Data &= (~(1 << Bit));
}
else //if bit is not set
{
Data |= (1 << Bit);
}
}
This logic is very simple and you would get a better logic than this. But this is a good program to start work wround bits. I think no explaination is required for this.
2. Program to reverse the bit order of an integer
void ReverseBitOrder()
{
for(i=0;i<32;i++)
{
p = data >> i; //'data' is the value to be reversed
t = p & 1; // 'p' and 't' are temporary variables
result = result | (t & 1);
result <<=1;
}
}
This is a good program to play with bits. Also, at firt time, it has taken some more time to do this. First i have tried on a paper. But after doing program only i could able to do because of debugging.
I think these are good programs to start work around bits in C.
Goooooooooood luccccccccccccck
----
Nice post. It has helped me. Thanks a lot.
ReplyDelete