Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

conversion form self defined type to byte array

Status
Not open for further replies.

stonee74

Technical User
Nov 12, 2001
49
0
0
CH
Hi,

How can I convert a self defined datatype into a byte array?

thanks a lot,
stonee
 
for example this struct: (header of a bitmap file)
struct BitmapFileHeader
{
public ushort bfType;
public int bfSize;
public ushort bfReserved1;
public ushort bfReserved2;
public int bfOffBits;
public static int Length = 14;

public byte[] ToByteArray()
{
byte[] ByteArray = new byte[Length];
BitConverter.GetBytes(bfType).CopyTo(ByteArray,0);
BitConverter.GetBytes(bfSize).CopyTo(ByteArray, 2);
BitConverter.GetBytes(bfReserved1).CopyTo(ByteArray, 6);
BitConverter.GetBytes(bfReserved2).CopyTo(ByteArray, 8);
BitConverter.GetBytes(bfOffBits).CopyTo(ByteArray, 10);
return ByteArray;
}

public void FromByteArray(byte[] ByteArray)
{
bfType = BitConverter.ToUInt16(ByteArray, 0);
bfSize = BitConverter.ToInt32(ByteArray, 2);
bfReserved1 = BitConverter.ToUInt16(ByteArray, 6);
bfReserved2 = BitConverter.ToUInt16(ByteArray, 8);
bfOffBits = BitConverter.ToInt32(ByteArray, 10);
}
};

I used it to read and write this structure to a file.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top