Open main menu

CDOT Wiki β

Changes

OOP344-Jason Quan C/C++ Programs & notes-20102

1,186 bytes added, 22:12, 28 June 2010
added bitwise operators set and unset bits to notes
</p>
 
==set and unset bits==
<p>
While I was studying for the OOP344 test, I created a small program that demonstrates how to set a bit or unset a bit. For example if the number is 1 and the binary is 000001. Therefore if I choose to set the bit 2 the binary will become 000011 and the number will become 3. However if I choose to unset 1 the binary will become 000010. Thus a set and unset bit function has been created. </p>
<pre>
#include <stdio.h>
#define mask 32
void printdata(int v, int m){
for(m;m>0;m = m >>1){
printf("%d",!!(v & m));
}
printf("\n");
}
 
/*set bit to one or zero and output the binary*/
void set(int* v, int num){
*v=((*v)^num); /*0^0=0 and 1^0=1* therefore the operator will set the bit to 1 or 0*/
printdata(*v,mask);
}
 
int main(){
int a;
int m;
do{
printf(" enter number(number>32 to quit):\n");
scanf("%d",&a);
if(a<32){
printdata(a,mask);
printf("the current number is: %d\n",a);
printf("set bit:\n");
scanf("%d",&m);
set(&a,m);
printf("The new number: %d\n", a);
printf("unset bit:\n");
scanf("%d",&m);
set(&a,m);
printf("The new Number: %d\n", a);
}
}while(a<32);
}
</pre>
1
edit