Run Code
|
API
|
Code Wall
|
Misc
|
Feedback
|
Login
|
Theme
|
Privacy
|
Patreon
BitArrays Are Cool
//Rextester.Program.Main is the entry point for your code. Don't change it. //Compiler version 4.0.30319.17929 for Microsoft (R) .NET Framework 4.5 using System; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; using System.Collections; namespace Rextester { public class Program { static Random Rand = new Random(); public static void Main(string[] args) { //converting byte --> bool[] as bits of a byte byte val = (byte)Rand.Next(256); BitArray t = new BitArray(new byte[]{val}); Console.WriteLine("The value is {0}", val); bool[] bits = new bool[8]; t.CopyTo(bits, 0); if(!BitConverter.IsLittleEndian) Array.Reverse(bits); //IMPORTANT! //printing out the bit array as a binary number Console.Write("Binary: "); for (int x = 7; x >= 0; x--) Console.Write(bits[x] ? "1" : "0"); Console.WriteLine(); //various binary operations can be done to the bool[] if(bits[7]) Console.WriteLine("Top bit is set"); //converting bool[] as bits --> byte byte[] temp = new byte[1]; t.CopyTo(temp, 0); Console.WriteLine("The value is still {0}", temp[0]); //using BitConverter to get bytes representing various types int ival = Rand.Next(); Console.WriteLine("\n\nThe new value is {0}", ival); byte[] ibytes = BitConverter.GetBytes(ival); //get the 4 bytes making up the integer Console.Write("Hex: "); for (int x = ibytes.Length - 1; x >= 0; x--) Console.Write(ibytes[x].ToString("x") + " "); //hexadecimal representation Console.WriteLine(); Console.Write("Binary: "); for(int x = ibytes.Length - 1; x >= 0; x--) { t = new BitArray(new byte[]{ibytes[x]}); //you can convert more than one byte, but for simplicity I'm doing one at a time t.CopyTo(bits, 0); if(BitConverter.IsLittleEndian) Array.Reverse(bits); //IMPORTANT! foreach (bool bit in bits) Console.Write(bit ? "1" : "0"); Console.Write(" "); } Console.WriteLine(); } } }
run
|
edit
|
history
|
help
0
Sam a,b and c
CodeAdvent
conter 1 in binnary number
john
Scope variables
Nullable type - Value Exception
0/1 Knapsack problem using Iterative Approach
Hello Demo
Added Carnival, List Matching
book iequatable