位操作

 1 using System.Collections.Generic;
 2 
 3 //位操作工具
 4 public class BitTool
 5 {
 6     /// <summary>
 7     /// 位设置
 8     /// </summary>
 9     /// <param name="num">检测数字</param>
10     /// <param name="pos">第几位,从1开始</param>
11     /// <returns></returns>
12     public static int BitSet(int num,ushort pos)
13     {
14         if (pos <= 0 || pos > 32)
15         {
16             return num;
17         }
18         return num | (0x00000001 << (pos - 1));
19     }
20 
21     /// <summary>
22     /// 位清理
23     /// </summary>
24     /// <param name="num">检测数字</param>
25     /// <param name="pos">第几位,从1开始</param>
26     /// <returns></returns>
27     public static int BitClear(int num, ushort pos)
28     {
29         if (pos <= 0 || pos > 32)
30         {
31             return num;
32         }
33         return num & (~(0x00000001 << (pos - 1)));
34     }
35 
36     /// <summary>
37     /// 位检测
38     /// </summary>
39     /// <param name="num">检测数字</param>
40     /// <param name="pos">第几位,从1开始</param>
41     /// <returns></returns>
42     public static bool BitTest(int num, ushort pos)
43     {
44         if (pos <= 0 || pos > 32)
45         {
46             return false;
47         }
48         return ((num >> (pos - 1)) & 0x00000001) == 1;
49     }
50 
51     /// <summary>
52     /// 获取一个十进制数位为1的索引数组 如num = 5,则返回[1,3]
53     /// </summary>
54     /// <param name="num">数字</param>
55     /// <returns></returns>
56     public static int[] GetIndexOfBit1(uint num) {
57         List<int> indexs = new List<int>();
58         if (num == 0) {
59             return indexs.ToArray();
60         }
61         int index = 0;
62         for (uint q = num; q > 0; q = q / 2 ){
63             uint m = q % 2;
64             index++;
65             if (m == 1){
66                 indexs.Add(index);
67             }
68         }
69         return indexs.ToArray();
70     }
71 }

 

posted @ 2019-05-30 20:13  青树  阅读(168)  评论(0编辑  收藏  举报