-2

for example

uint <- 1

I want to get

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

if

uint <- 8

get it

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

Just format by bit , How can I do?

TimChang
  • 2,249
  • 13
  • 25
  • 2
    `var binaryString = Convert.ToString(someInteger, 2)` The second argument specifies base 2 a.k.a binary.. – John Wu Jul 06 '20 at 06:34
  • And at which point did you fail when you tried? And `0` and `1` are no `bool` values, please be specific about your requirements, do you want a `boo[]` or a string of ones and zeros? – René Vogt Jul 06 '20 at 06:34

3 Answers3

2

You can try Linq for this:

  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));

Outcome:

   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

If you want bool[] result the query can be

  bool[] result = Enumerable
    .Range(0, sizeof(uint) * 8)
    .Reverse()
    .Select(i => (source & (1 << i)) != 0)
    .ToArray();
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
1
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);
        }       
    }
}

Note that this will push the lsbit first.

bavaza
  • 10,319
  • 10
  • 64
  • 103
1

And another option: Use Convert.ToString(Int64, Int32) to create the binary representation of the uint value (a built in implicit conversion from UInt32 to Int64 exists, so no problem there).
Then add the leading zeros using string's PadLeft(int, char)
Then use Select to convert the chars to boolean values - and finally, ToArray():

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

You can see a live demo on rextester

Zohar Peled
  • 79,642
  • 10
  • 69
  • 121