Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <conio.h>
- #define nl printf("\n")
- void showBit (unsigned int);
- void setBit (unsigned int *, int);
- void clearBit (unsigned int *, int);
- int isSet (unsigned int a, int pos);
- int showBit2 (unsigned int a);
- void invertBit (unsigned int *a, int pos);
- int numberofsetBit (unsigned int a);
- int main (void)
- {
- unsigned int i=3;
- unsigned int pos=5;
- int set=0;
- showBit2 (i);
- nl;
- setBit (&i,pos);
- showBit (i);
- nl;
- printf ("%X",i);
- clearBit (&i, pos);
- nl;
- showBit (i);
- if (isSet (i,pos))
- clearBit (&i,pos);
- nl;
- showBit (i);
- invertBit (&i, 10);
- nl;
- showBit (i);
- nl;
- set=numberofsetBit (i);
- printf ("%d",set);
- getch ();
- return 0;
- }
- void showBit (unsigned int a)
- {
- unsigned int mask=1;
- int i=0;
- mask<<=sizeof(int)*8-1; //1 ganz nach links
- for (i=0; i<sizeof(int)*8; i++)
- {
- // if ((a&mask)==mask)
- if (a&mask)
- printf ("%c",'1');
- else
- printf ("%c",'0');
- mask >>=1; //eine Stelle nach rechts
- }
- }
- void setBit (unsigned int *a, int pos)
- {
- unsigned int mask=1;
- if (pos>=0 && pos<sizeof(int)*8)
- {
- mask=mask<<pos;
- *a=*a|mask;
- }
- }
- void clearBit (unsigned int *a, int pos)
- {
- unsigned int mask=1;
- if (pos>=0 && pos<sizeof(int)*8)
- {
- mask=mask<<pos; //1 auf die Position "pos" bringen
- mask=~mask;
- *a=*a&mask;
- }
- }
- int isSet (unsigned int a, int pos)
- {
- int control=0;
- unsigned int mask=1;
- if (pos>=0 && pos<sizeof(int)*8)
- {
- mask=mask<<pos; //1 auf die Position "pos" bringen
- control=a&mask;
- }
- return control;
- }
- int showBit2 (unsigned int a)
- {
- int i=sizeof(a)*8-1;
- for (;i>=0; i--)
- {
- if (isSet(a,i))
- printf ("%c",'1');
- else
- printf ("%c",'0');
- }
- }
- void invertBit (unsigned int *a, int pos)
- {
- unsigned int mask=1;
- if (pos>=0 && pos<sizeof(int)*8)
- {
- mask=mask<<pos;
- *a=*a^mask;
- }
- }
- int numberofsetBit (unsigned int a)
- {
- unsigned int mask=1;
- int z=0;
- int pos=0;
- do
- {
- if(isSet (a,pos))
- z++;
- pos++;
- }while (pos<sizeof(int)*8);
- return z;
- }
Advertisement
Add Comment
Please, Sign In to add comment