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.
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.
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.
To convert an integer to string in C#, use the ToString() method.
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.
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();
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With