从整数初始化 BitArray

OzB*_*OzB 1 c#

我正在尝试从整数值初始化 System.BitArray 实例。但是,看起来我没有得到正确的值。

我的代码是

        var b = new BitArray(BitConverter.GetBytes(0xfa2));
        for (int i = 0; i < b.Count; i++)
        {
            char c = b[i] ? '1' : '0';
            Console.Write(c);
        }
        Console.WriteLine();
Run Code Online (Sandbox Code Playgroud)

我也试过没有 BitConverter:

        var b = new BitArray(new int[] { 0xfa2 });
Run Code Online (Sandbox Code Playgroud)

但这些尝试似乎都没有奏效。这些是这里建议的尝试:Convert int to a bit array in .NET

我的输出:01000101111100000000000000000000。预期的输出:111110100010。

任何帮助将不胜感激!

vcs*_*nes 5

你从错误的方向循环。尝试这个:

    var b = new BitArray(BitConverter.GetBytes(0xfa2));
    for (int i = b.Count-1; i >= 0; i--)
    {
        char c = b[i] ? '1' : '0';
        Console.Write(c);
    }
    Console.WriteLine();
Run Code Online (Sandbox Code Playgroud)