Tuesday, October 17, 2006

Convert to a Byte Array

If you need to convert a basic value type to a byte array then you've come to the right place..

The System.BitConverter class provides a cool mechanism for this conversion process.

The exception is the decimal value type, use the System.IO.MemoryStream object.

System.BitConverter.GetBytes returns the conversion as an array of bytes. It is overloaded to take many datatypes. It also contains static methods to convert from a byte array to a datatype.

For decimals --> ByteArray use System.IO.BinaryWriter then use the MemoryStream.ToArray.

For ByteArray --> Decimal use the System.IO.BinaryReader



Code : Decimal to ByteArray


public static byte[] ConvertDecimalToByteArray(decimal src){
--using(MemoryStream stream = new MemoryStream()){
----using(BinaryWriter writer = new BinaryWriter(stream)){
------writer.Write(src);
------return stream.ToArray();
----}
--}
}


Code: ByteArray to Decimal

public static decimal ConvertByteArrayToDecimal(byte[] src){
--using(MemoryStream stream = new MemorStream(stc)){
----using (BinaryReader reader = new BinaryReader(stream)){
------return reader.ReadDecimal();
----}
--}
}


Code: Other Datatypes to Byte Array

byte[] b =null;

b=BitConverter.GetBytes("THIS IS A STRING");
BitConverter.ToString(b);

No comments: