new BinaryWriter(stream) and Write method
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;
b = BitConverter.GetBytes(true);
Console.WriteLine(BitConverter.ToString(b));
Console.WriteLine(BitConverter.ToBoolean(b, 0));
b = BitConverter.GetBytes(3678);
Console.WriteLine(BitConverter.ToString(b));
Console.WriteLine(BitConverter.ToInt32(b, 0));
b = DecimalToByteArray(12345678.123456m);
Console.WriteLine(BitConverter.ToString(b));
Console.WriteLine(ByteArrayToDecimal(b));
}
}
Related examples in the same category