473,508 Members | 2,250 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 32004
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
1722
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
1954
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
10136
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
18863
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
4002
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
3452
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
29098
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
2140
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
3818
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...
0
7227
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
7391
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
7501
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
5633
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
1
5056
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
4713
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
3204
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
1
768
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
424
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence...

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.