Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert int to a bit array in .NET

Tags:

c#

.net

How can I convert an int to a bit array?

If I e.g. have an int with the value 3 I want an array, that has the length 8 and that looks like this:

0 0 0 0 0 0 1 1 

Each of these numbers are in a separate slot in the array that have the size 8.

like image 576
Afra Avatar asked Jul 20 '11 07:07

Afra


People also ask

How do you change an int to a bit?

To convert integer to binary, start with the integer in question and divide it by 2 keeping notice of the quotient and the remainder. Continue dividing the quotient by 2 until you get a quotient of zero. Then just write out the remainders in the reverse order.

What is bit array in C#?

Advertisements. The BitArray class manages a compact array of bit values, which are represented as Booleans, where true indicates that the bit is on (1) and false indicates the bit is off (0). It is used when you need to store the bits but do not know the number of bits in advance.

How do I convert an int to a string in C#?

To convert an integer to string in C#, use the ToString() method.

Can we convert int to string in C# with example?

C# int to string other examples The following example provides other ways to the int to string conversion in C#. int val = 4; string msg = "There are " + Convert. ToString(val) + " hawks"; string msg2 = string. Format("There are {0} hawks", val); string msg3 = $"There are {val} hawks"; Console.


2 Answers

Use the BitArray class.

int value = 3; BitArray b = new BitArray(new int[] { value }); 

If you want to get an array for the bits, you can use the BitArray.CopyTo method with a bool[] array.

bool[] bits = new bool[b.Count]; b.CopyTo(bits, 0); 

Note that the bits will be stored from least significant to most significant, so you may wish to use Array.Reverse.

And finally, if you want get 0s and 1s for each bit instead of booleans (I'm using a byte to store each bit; less wasteful than an int):

byte[] bitValues = bits.Select(bit => (byte)(bit ? 1 : 0)).ToArray(); 
like image 58
Sven Avatar answered Sep 21 '22 15:09

Sven


To convert the int 'x'

int x = 3; 

One way, by manipulation on the int :

string s = Convert.ToString(x, 2); //Convert to binary in a string  int[] bits= s.PadLeft(8, '0') // Add 0's from left              .Select(c => int.Parse(c.ToString())) // convert each char to int              .ToArray(); // Convert IEnumerable from select to Array 

Alternatively, by using the BitArray class-

BitArray b = new BitArray(new byte[] { x }); int[] bits = b.Cast<bool>().Select(bit => bit ? 1 : 0).ToArray(); 
like image 31
Maxim Avatar answered Sep 21 '22 15:09

Maxim