Mega Code Archive

 
Categories / C# Book / 02 Essential Types
 

0323 Basic Value Types to Byte Arrays

System.BitConverter class can convert most basic value types to and from byte arrays. using System; using System.IO; class MainClass { public static byte[] DecimalToByteArray(decimal src) { using (MemoryStream stream = new MemoryStream()) { using (BinaryWriter writer = new BinaryWriter(stream)) { writer.Write(src); return stream.ToArray(); } } } public static decimal ByteArrayToDecimal(byte[] src) { using (MemoryStream stream = new MemoryStream(src)) { using (BinaryReader reader = new BinaryReader(stream)) { return reader.ReadDecimal(); } } } public static void Main() { byte[] b = null; // Convert a bool to a byte array and display. b = BitConverter.GetBytes(true); Console.WriteLine(BitConverter.ToString(b)); // Convert a byte array to a bool and display. Console.WriteLine(BitConverter.ToBoolean(b, 0)); // Convert an int to a byte array and display. b = BitConverter.GetBytes(3678); Console.WriteLine(BitConverter.ToString(b)); // Convert a byte array to an int and display. Console.WriteLine(BitConverter.ToInt32(b, 0)); // Convert a decimal to a byte array and display. b = DecimalToByteArray(285998345545.563846696m); Console.WriteLine(BitConverter.ToString(b)); // Convert a byte array to a decimal and display. Console.WriteLine(ByteArrayToDecimal(b)); } } The output: 01 True 5E-0E-00-00 3678 28-38-C1-50-FD-3B-06-81-0F-00-00-00-00-00-09-00 285998345545.563846696