473,382 Members | 1,658 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,382 software developers and data experts.

from byte[] to structure

Can anyone tell me how to get data from a byte array into the following
structure?

[Serializable]
[StructLayout(LayoutKind.Sequential)]
public struct MESSAGE_LOG_HEADER_STRUCT2
{
public DateTime dtTimeStamp;
public Int32 dSerialNumber;
[MarshalAs(UnmanagedType.ByValArray, SizeConst=8)]
public byte[] strMCFirmwareVersion;
public Int32 dMCFirmwareChecksum;
[MarshalAs(UnmanagedType.ByValArray, SizeConst=8)]
public byte[] strSBCSoftwareVersion;
public Int32 dSBCSoftwareChecksum;
[MarshalAs(UnmanagedType.ByValArray, SizeConst=32)]
public byte[] strBarcode;
}

I have tried the following code, but I get the exception "BinaryFormatter
Version incompatibility." when it executes.

MemoryStream ms = new MemoryStream(bytes); // bytes is a byte[]
BinaryFormatter bf = new BinaryFormatter();
m_CompleteIllumStateMsg = (MIX_CompleteIllumStateMsg)bf.Deserialize(ms); //
m_CompleteIllumStateMsg is a MESSAGE_LOG_HEADER_STRUCT2
Nov 16 '05 #1
3 31984
Hi Ben,

"Ben Terry" <bt@charter.net> wrote in message
news:u7**************@TK2MSFTNGP12.phx.gbl...
Can anyone tell me how to get data from a byte array into the following
structure?


Feel free to use this method:

public static object RawDeserialize( byte[] rawData, int position, Type
anyType )
{
int rawsize = Marshal.SizeOf( anyType );
if( rawsize > rawData.Length )
return null;
IntPtr buffer = Marshal.AllocHGlobal( rawsize );
Marshal.Copy( rawData, position, buffer, rawsize );
object retobj = Marshal.PtrToStructure( buffer, anyType );
Marshal.FreeHGlobal( buffer );
return retobj;
}

the position is the position into the byte array to start deserializing
from, and the
type is the type of the structure - typof(MESSAGE_LOG_HEADER_STRUCT2).
Remember to cast the return value to the same type too.

And if you want to do vice versa, use this one:

public static byte[] RawSerialize( object anything )
{
int rawSize = Marshal.SizeOf( anything );
IntPtr buffer = Marshal.AllocHGlobal( rawSize );
Marshal.StructureToPtr( anything, buffer, false );
byte[] rawDatas = new byte[ rawSize ];
Marshal.Copy( buffer, rawDatas, 0, rawSize );
Marshal.FreeHGlobal( buffer );
return rawDatas;
}

--
Lars Wilhelmsen
http://www.sral.org/
Software Engineer
Teleplan A/S, Norway
Nov 16 '05 #2
Excellent! Thank you so much.

"Lars Wilhelmsen" <la*****@NOSPAM.ifi.uio.no> wrote in message
news:uV*************@TK2MSFTNGP12.phx.gbl...
Hi Ben,

"Ben Terry" <bt@charter.net> wrote in message
news:u7**************@TK2MSFTNGP12.phx.gbl...
Can anyone tell me how to get data from a byte array into the following
structure?


Feel free to use this method:

public static object RawDeserialize( byte[] rawData, int position, Type
anyType )
{
int rawsize = Marshal.SizeOf( anyType );
if( rawsize > rawData.Length )
return null;
IntPtr buffer = Marshal.AllocHGlobal( rawsize );
Marshal.Copy( rawData, position, buffer, rawsize );
object retobj = Marshal.PtrToStructure( buffer, anyType );
Marshal.FreeHGlobal( buffer );
return retobj;
}

the position is the position into the byte array to start deserializing
from, and the
type is the type of the structure - typof(MESSAGE_LOG_HEADER_STRUCT2).
Remember to cast the return value to the same type too.

And if you want to do vice versa, use this one:

public static byte[] RawSerialize( object anything )
{
int rawSize = Marshal.SizeOf( anything );
IntPtr buffer = Marshal.AllocHGlobal( rawSize );
Marshal.StructureToPtr( anything, buffer, false );
byte[] rawDatas = new byte[ rawSize ];
Marshal.Copy( buffer, rawDatas, 0, rawSize );
Marshal.FreeHGlobal( buffer );
return rawDatas;
}

--
Lars Wilhelmsen
http://www.sral.org/
Software Engineer
Teleplan A/S, Norway

Nov 16 '05 #3
Hi,
public YourStruct BytesToStruct(byte[] dataIn)
{
GCHandle hDataIn = GCHandle.Alloc(dataIn, GCHandleType.Pinned);
YourStruct ys =
(YourStruct)Marshal.PtrToStructure(hDataIn.AddrOfP innedObject(),
typeof(YourStruct));
hDataIn.Free();
return ys;
}

HTH,
greetings
"Ben Terry" <bt@charter.net> wrote in message
news:u7**************@TK2MSFTNGP12.phx.gbl...
Can anyone tell me how to get data from a byte array into the following
structure?

[Serializable]
[StructLayout(LayoutKind.Sequential)]
public struct MESSAGE_LOG_HEADER_STRUCT2
{
public DateTime dtTimeStamp;
public Int32 dSerialNumber;
[MarshalAs(UnmanagedType.ByValArray, SizeConst=8)]
public byte[] strMCFirmwareVersion;
public Int32 dMCFirmwareChecksum;
[MarshalAs(UnmanagedType.ByValArray, SizeConst=8)]
public byte[] strSBCSoftwareVersion;
public Int32 dSBCSoftwareChecksum;
[MarshalAs(UnmanagedType.ByValArray, SizeConst=32)]
public byte[] strBarcode;
}

I have tried the following code, but I get the exception "BinaryFormatter
Version incompatibility." when it executes.

MemoryStream ms = new MemoryStream(bytes); // bytes is a byte[]
BinaryFormatter bf = new BinaryFormatter();
m_CompleteIllumStateMsg = (MIX_CompleteIllumStateMsg)bf.Deserialize(ms); // m_CompleteIllumStateMsg is a MESSAGE_LOG_HEADER_STRUCT2

Nov 16 '05 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

7
by: drewnoakes | last post by:
I have an application that performs custom deserialisation of object state from byte arrays. This happens very regularly, so needs to be fast. In addition, most of the strings repeat, meaning I'm...
2
by: Tim Conner | last post by:
Which functions are available to move a part from byte into another byte ? Let's say I have a byte of 20 and another of 40. And I want to move 5th to 15th from the first byte into occupping bytes...
6
by: Ricardo Quintanilla | last post by:
i have a code that sends data to a socket listening over as400 platform, the socket responds to me as a "byte array". then i need to convert the "byte array" into a string. the problem is that...
8
by: Kenny ODell | last post by:
I do not know how to convert from a byte array to a float, and back again. I read data from a serial port into a byte (entire command structure which I parse). I am able to sift the data and...
4
by: movieknight | last post by:
Hi, I have an application that stores raw .wav files (and also jpgs/bitmaps) within strings, and I need to sometimes convert these strings to byte arrays, and sometimes go from byte arrays back...
5
by: moni | last post by:
Hey, My buffer contains a short int, some char, and a structure in form of a byte array. Read the string as: TextBox4.Text = System.Text.Encoding.ASCII.GetString(buffer1, 0, 31); Read...
2
by: valentin tihomirov | last post by:
The conversion shold be trivial -- no conversion copy. In essense, both types are pointers to byte array. The difference is purely semantical. unsafe { byte b = 1; byte data = &b; } ...
2
by: Oki | last post by:
I appreciate any help; I'm currently getting a problem with trying to concatenate a single char from a structure to an existing string. Basically, the problem is here: strcat( res, morse_c.letter...
3
by: efdeugenio | last post by:
Hi, I will really appreciate if someone cans help me with this: I have a managed c++ class that I am calling from C#. The declaration of a function in this class is: bool CanAddTemplate(unsigned...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.