C# int值与(bit位为1的位号数组(1~32))的互相转换
1 /// <summary> 2 /// 指定bit位的数字出现,则将该位,置为1,最后获取转换结果int值 3 /// </summary> 4 /// <param name="arr">指定bit位的数字,集合</param> 5 /// <returns></returns> 6 /// <exception cref="ArgumentException">非法参数</exception> 7 public static int ConvertIntSetToInt(int[] arr) 8 { 9 int result = 0; 10 foreach (var item in arr) 11 { 12 if (item >= 1 && item <= 32) 13 { 14 15 result |= 1 << (item - 1); 16 } 17 else 18 { 19 throw new ArgumentException("Number must be between 1 and 32 (inclusive)."); 20 } 21 } 22 return result; 23 } 24 /// <summary> 25 /// int值二进制指定bit位为1,则向数组中添加该指定位数。 26 /// </summary> 27 /// <param name="mask">int值</param> 28 /// <returns></returns> 29 public static int[] ConvertIntToIntSet(int mask) 30 { 31 List<int> list = new List<int>(); 32 byte[] bytes = BitConverter.GetBytes(mask); 33 List<char> chars = new List<char>(); 34 foreach (var item in bytes) 35 { 36 chars.AddRange(Convert.ToString(item, 2).PadLeft(8, '0').Reverse()); 37 } 38 for (int i = 0; i < chars.Count; i++) 39 { 40 if (chars[i] == '1') 41 { 42 list.Add(i + 1); 43 } 44 } 45 return list.ToArray(); 46 }
测试代码:
// bit位为1的位号数组,转实际int值 int value = ConvertIntSetToInt(new int[] { 1, 3, 4, 6 }); Console.WriteLine(value); Console.WriteLine("---------------------"); byte[] arr = BitConverter.GetBytes(value); List<char> str = new List<char>(); foreach (var item in arr) { // 转为字符串格式,从左向右依次为1-32bit位 str.AddRange(Convert.ToString(item, 2).PadLeft(8, '0').Reverse().ToList()); } Console.WriteLine(new string(str.ToArray())); Console.WriteLine("---------------------"); // 实际int值转bit位为1的位号数组 int[] cols = ConvertIntToIntSet(value); Console.WriteLine(string.Join(' ', cols));
测试结果:


浙公网安备 33010602011771号