Prev Up Next
Go backward to Manipulação de bits
Go up to Alguns exercícios a exemplos dados nas aulas teóricas
Go forward to Fibonacci era recursivo

Manipulação de bits, continuação



 // -----------------------------------------------------------------------------
 // Manipulação de bits II
 // Acesso aos bits individuais dos elementos de um vector

 #define MAX 10

 // array como parametros
 void set(int,int);
 int  get(int);
 void display(void);

 main(){
   int i,b;
   while(1){
     printf("i = ? ");
     scanf("%d",&i);
     printf("put 0 or 1? ");
     scanf("%d",&b);
     set(i,b);
     display();
   }
 }

 unsigned char x[MAX];
 unsigned char  mask[ ]={1,2,4,8,16,32,64,128};

 void set(int i,int a){
   int t=i/8, pos=i%8;
   if(a)
     x[t] = x[t] | mask[pos];
   else
     x[t] = x[t] & ~mask[pos];
 }

 int  get(int i){
   int t=i/8, pos=i%8;
   if(x[t]&mask[pos])
     return(1);
   else
     return(0);
 }

 void display(void){
   int i;
   for(i=0;i<MAX;i++){
     int j;
     for(j=0;j<8;j++){
       if(get(8*i+j))
 	printf(" 1");
       else
 	printf(" 0");
     }
       printf("  ");
    }
    printf("\n");
 }
 /*
 i = ? 0
 put 0 or 1? 1
  1 0 0 0 0 0 0 0   0 0 0 0 0 0 0 0   0 0 0 0 0 0 0 0   0 0 0 0 0 0 0 0
 i = ? 1
 put 0 or 1? 1
  1 1 0 0 0 0 0 0   0 0 0 0 0 0 0 0   0 0 0 0 0 0 0 0   0 0 0 0 0 0 0 0
 i = ? 2
 put 0 or 1? 1
  1 1 1 0 0 0 0 0   0 0 0 0 0 0 0 0   0 0 0 0 0 0 0 0   0 0 0 0 0 0 0 0
 i = ? 1
 put 0 or 1? 0
  1 0 1 0 0 0 0 0   0 0 0 0 0 0 0 0   0 0 0 0 0 0 0 0   0 0 0 0 0 0 0 0
 */


Prev Up Next