Bit Operation (Modify Bit Data)

  1 #include <stdio.h>
  2 #include <stdlib.h>
  3 #include <math.h>
  4 
  5 #define BYTETOBINARYPATTERN "%d%d%d%d%d%d%d%d"
  6 
  7 #define BYTETOBINARY(byte) \
  8     (byte & 0x80 ? 1 : 0), \
  9     (byte & 0x40 ? 1 : 0), \
 10     (byte & 0x20 ? 1 : 0), \
 11     (byte & 0x10 ? 1 : 0), \
 12     (byte & 0x08 ? 1 : 0), \
 13     (byte & 0x04 ? 1 : 0), \
 14     (byte & 0x02 ? 1 : 0), \
 15     (byte & 0x01 ? 1 : 0)
 16 
 17 #define PRINTBIN(x) printf(BYTETOBINARYPATTERN, BYTETOBINARY(x));
 18 
 19 void setlsbs(unsigned char *p, unsigned char b0);
 20 unsigned char getlsbs(unsigned char *p);
 21 
 22 
 23 int main(int argc, char **argv)
 24 {
 25     int seed;
 26     int i;
 27     unsigned char p[8];
 28     unsigned char byte0 = random()%256;    
 29     unsigned char return_val;
 30 
 31     sscanf(argv[1],"%d",&seed);
 32     srandom(seed);
 33     
 34     for(i = 0; i<8;i++)
 35     {
 36         p[i] = random()%256;
 37     }
 38     
 39     for(i = 0; i<8; i++)
 40     {
 41         printf("p[%d] = %d ",i,p[i]);
 42         printf("binary format: "); PRINTBIN(p[i]); printf("\n");        
 43     }
 44 
 45     printf("byte0 = %d ",byte0);
 46     printf("binary format: "); PRINTBIN(byte0); printf("\n");    
 47 
 48     setlsbs(p,byte0);
 49 
 50     for(i = 0; i<8; i++)
 51     {
 52         printf("p[%d] = %d ",i,p[i]);
 53         printf("binary format: "); PRINTBIN(p[i]); printf("\n");        
 54     }
 55 
 56     return_val = getlsbs(p);
 57 
 58     printf("Return value of the call to getlsbs(): %d ", return_val);    
 59     printf("binary format: "); PRINTBIN(return_val); printf("\n");    
 60 
 61     return 0;
 62 }
 63 
 64 
 65 
 66 void setlsbs(unsigned char *p, unsigned char b0)
 67 {
 68     int i;
 69     int n[8];
 70     n[0]  = (b0 & 0x01) == 0x01 ? 1:0;
 71     n[1]  = (b0 & 0x02) == 0x02 ? 1:0;
 72     n[2]  = (b0 & 0x04) == 0x04 ? 1:0;
 73     n[3]  = (b0 & 0x08) == 0x08 ? 1:0;
 74     n[4]  = (b0 & 0x10) == 0x10 ? 1:0;
 75     n[5]  = (b0 & 0x20) == 0x20 ? 1:0;
 76     n[6]  = (b0 & 0x40) == 0x40 ? 1:0;
 77     n[7]  = (b0 & 0x80) == 0x80 ? 1:0;
 78     
 79     for(i = 0; i<8;i++)
 80     {
 81         /* modify the least significant bit of the byte */
 82         int index = 1<<0; 
 83         if(n[i])
 84         {
 85             p[i] |= index;
 86         }
 87         else
 88         {
 89             p[i] &= ~index;        
 90         }
 91     }    
 92 }
 93 
 94 unsigned char getlsbs(unsigned char *p)
 95 {
 96     unsigned char ret_val = 0;
 97     int i;
 98     int temp;
 99     
100     for(i = 0; i<8 ;i++)
101     {
102         temp = ( (p[i] & 0x01) == 0x01 ? pow(2,i):0 );
103         ret_val += temp;        
104     }
105 
106     return ret_val;        
107 }

猜你喜欢

转载自www.cnblogs.com/JasperZhao/p/12914107.html
BIT