数组数据整体按位左移或右移一位

数组数据整体按位左移或右移一位

 1 #include <stdio.h>
 2 
 3 #define MSB        0x80
 4 #define LSB        0x01
 5 
 6 // 数组数据整体按位左移一位
 7 int left_shift(unsigned char *str, int len)
 8 {
 9     int i;
10     
11     for(i = 1; i <= len; i++)
12     {
13         str[i-1] = str[i-1] << 1;
14         
15         if(i < len && str[i] & MSB)
16         {
17             str[i-1] = str[i-1] | LSB;    
18         }    
19     }
20     
21     return 0;
22 }
23 
24 // 数组数据整体按位右移一位
25 int right_shift(unsigned char *str, int len)
26 {
27     int i;
28     
29     for(i = len-1; i >= 0; i--)
30     {
31         str[i] = str[i] >> 1;
32         if(i > 0 && str[i-1] & LSB)
33         {
34             str[i] = str[i] | MSB;    
35         }    
36     }
37     
38     return 0;    
39 }
40 
41 int main(void)
42 {
43     int i;
44     unsigned char x1[] = {0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01};
45     unsigned char x2[] = {0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01};
46 
47     left_shift(x1, sizeof(x1)/sizeof(x1[0]));
48     
49     right_shift(x2, sizeof(x2)/sizeof(x2[0]));
50     
51     for(i = 0; i < sizeof(x1)/sizeof(x1[0]); i++)
52         printf("%02x ", x1[i]);
53     printf("
");
54     
55     for(i = 0; i < sizeof(x2)/sizeof(x2[0]); i++)
56         printf("%02x ", x2[i]);    
57         
58     
59     return 0;    
60 }
原文地址:https://www.cnblogs.com/utank/p/5773157.html