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?
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?
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();
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.
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