The static method GetBytes of the BitConverter class provides overloads that take most of the standard value types and return the value encoded as an array of bytes. Support is provided for the bool, char, double, short, int, long, float, ushort, uint, and ulong data types. BitConverter also provides a set of static methods that support the conversion of byte arrays to each of the standard value types; these are named ToBoolean, ToUInt32, ToDouble, and so on. The following code (taken from the sample file ByteConversionExample.cs) demonstrates the use of BitConverter to convert a bool and an int to and from a byte array. The second argument to each of the ToBoolean and ToInt32 methods is a zero-based offset into the byte array where the BitConverter should start taking the bytes to create the data value.
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));
Unfortunately, BitConverter does not provide support for converting the decimal type. Instead, the following code shows how to convert a decimal to a byte array using a MemoryStream and a BinaryWriter.
// Create a byte array from a decimal public static byte[] DecimalToByteArray (decimal src) { // Create a MemoryStream as a buffer to hold the binary data using (MemoryStream stream = new MemoryStream()) { // Create a BinaryWriter to write binary data to the stream using (BinaryWriter writer = new BinaryWriter(stream)) { // Write the decimal to the BinaryWriter/MemoryStream writer.Write(src); // Return the byte representation of the decimal return stream.ToArray(); } } }
To convert a byte array to a decimal, use a BinaryReader to read from the MemoryStream, as shown in this code.
// Create a decimal from a byte array public static decimal ByteArrayToDecimal (byte[] src) { // Create a MemoryStream containing the byte array using (MemoryStream stream = new MemoryStream(src)) { // Create a BinaryReader to read the decimal from the stream using (BinaryReader reader = new BinaryReader(stream)) { // Read and return the decimal from the // BinaryReader/MemoryStream return reader.ReadDecimal(); } } }
No comments:
Post a Comment