【问题标题】:How to convert uint to bool array?如何将 uint 转换为 bool 数组?
【发布时间】:2020-07-06 06:31:24
【问题描述】:

例如

uint <- 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 1

如果

uint <- 8

得到它

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 1 0 0 0

按位格式化,怎么办?

【问题讨论】:

  • var binaryString = Convert.ToString(someInteger, 2) 第二个参数指定base 2 a.k.a binary..
  • 你在什么时候尝试失败了?而01 不是bool 值,请具体说明您的要求,您想要boo[] 还是一串1 和0?

标签: c# bit uint


【解决方案1】:

您可以为此尝试 Linq

  using System.Linq;

  ...

  uint source = 8;

  int[] result = Enumerable
    .Range(0, sizeof(uint) * 8)
    .Reverse()
    .Select(i => (source & (1 << i)) == 0 ? 0 : 1)
    .ToArray();

  Console.Write(string.Join(" ", result));

结果:

   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 1 0 0 0

如果你想bool[] result查询可以

  bool[] result = Enumerable
    .Range(0, sizeof(uint) * 8)
    .Reverse()
    .Select(i => (source & (1 << i)) != 0)
    .ToArray();

【讨论】:

  • 爱上 Linq :-)
【解决方案2】:
using System;
using System.Collections.Generic;
                    
public class Program
{
    public static void Main()
    {
        uint x = 1;
        List<bool> result = new List<bool>();
        for(int i = 0; i < 32; ++i)
        {
            bool isBitSet = ((x >> i) & 0x01) > 0;
            result.Add(isBitSet);
        }       
    }
}

请注意,这将首先推送 lsbit。

【讨论】:

    【解决方案3】:

    还有一个选择: 使用Convert.ToString(Int64, Int32) 创建uint 值的二进制表示(built in implicit conversion from UInt32 to Int64 存在,所以没有问题)。
    然后使用字符串的 PadLeft(int, char)
    添加前导零 然后使用Select 将字符转换为布尔值 - 最后是ToArray()

    static bool[] To32WithSpaces(uint number)
    {
        return Convert.ToString(number, 2)
            .PadLeft(32, '0')
            .Select(c => c=='1')
            .ToArray();
    }
    

    您可以在rextester 上观看现场演示

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-11-13
      • 1970-01-01
      • 2011-05-25
      • 1970-01-01
      • 1970-01-01
      • 2015-06-12
      • 2015-08-29
      • 1970-01-01
      相关资源
      最近更新 更多