473,569 Members | 2,729 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Convert parts of byte[] to struct

I have a huge byte array from another API that contains structs of differing
sizes. I'd like to create n structs based on data in the byte array. But
how? For example, if I want to take bytes 40-56 and create struct Foo from
them...how do I do this? You can assume I know how to create the properly
aligned struct.

Thanks

Amil
Nov 16 '05 #1
5 5315
You should use unsafe in combination with fixed in the following manner:
STRUCT strct;
byte[] MyArray = new byte[100];
unsafe
{
fixed(byte *pPtr = &MyArray[0])
{
STRUCT *ps = &strct;
*ps = *(STRUCT*)(pPtr + 53);
}
}

Note that your struct MUST include only value types so the memory layout
will directly represent the struct variables.

"Amil Hanish" wrote:
I have a huge byte array from another API that contains structs of differing
sizes. I'd like to create n structs based on data in the byte array. But
how? For example, if I want to take bytes 40-56 and create struct Foo from
them...how do I do this? You can assume I know how to create the properly
aligned struct.

Thanks

Amil

Nov 16 '05 #2
AND you should use:
[ StructLayout( LayoutKind.Sequ ential )]
"Nadav" <Na***@discussi ons.microsoft.c om> wrote in message
news:05******** *************** ***********@mic rosoft.com...
You should use unsafe in combination with fixed in the following manner:
STRUCT strct;
byte[] MyArray = new byte[100];
unsafe
{
fixed(byte *pPtr = &MyArray[0])
{
STRUCT *ps = &strct;
*ps = *(STRUCT*)(pPtr + 53);
}
}

Note that your struct MUST include only value types so the memory layout
will directly represent the struct variables.

"Amil Hanish" wrote:
I have a huge byte array from another API that contains structs of
differing
sizes. I'd like to create n structs based on data in the byte array.
But
how? For example, if I want to take bytes 40-56 and create struct Foo
from
them...how do I do this? You can assume I know how to create the
properly
aligned struct.

Thanks

Amil

Nov 16 '05 #3
You may utilize the features of System.Runtime. InteropServices .Marshal:

byte [] buff = new byte [Marshal.SizeOf( typeof(MYSTRUCT ))];
/* Put data into buffer here. */
IntPtr ptr = Marshal.AllocHG lobal(buff.Leng th);
Marshal.Copy(bu ff, 0x0, ptr, buff.Length);
MYSTRUCT myStruct = (MYSTRUCT) Marshal.PtrToSt ructure(ptr,
typeof(MYSTRUCT ));
Marshal.FreeHGl obal(ptr);
If you are OK with using "unsafe" code, i think this is the superior version
(you will have to compile with the /unsafe switch):

MYSTRUCT myStruct;
byte [] buff = new byte [sizeof(MYSTRUCT )];
/* Put data into buffer here. */
unsafe
{
fixed (byte * pBuff = buff)
myStruct = * ((MYSTRUCT *) pBuff);
}
Remember to explicitly specify that the members of the struct must not
be organized in another way than in the order that they are defined.
This is done with the System.Runtime. InteropServices .StructLayoutAt tribute
attribute:

[ StructLayout( LayoutKind.Sequ ential, Pack = 0x1 ) ]
struct MYSTRUCT
{
....
}
--
Regards,
Dennis JD Myrén
Oslo Kodebureau
"Amil Hanish" <am********@hot mail.com> wrote in message
news:uJ******** *****@TK2MSFTNG P10.phx.gbl...
I have a huge byte array from another API that contains structs of
differing
sizes. I'd like to create n structs based on data in the byte array. But
how? For example, if I want to take bytes 40-56 and create struct Foo
from
them...how do I do this? You can assume I know how to create the properly
aligned struct.

Thanks

Amil

Nov 16 '05 #4
Just a little modification:
MYSTRUCT myStruct;
byte [] buff = new byte [sizeof(MYSTRUCT )];
/* Put data into buffer here. */
unsafe
{
fixed (byte * pBuff = buff)
myStruct = * ((MYSTRUCT *) pBuff);
}

should be:

MYSTRUCT myStruct;
unsafe
{
byte [] buff = new byte [sizeof(MYSTRUCT )];
/* Put data into buffer here. */
fixed (byte * pBuff = buff)
myStruct = * ((MYSTRUCT *) pBuff);
}
--
Regards,
Dennis JD Myrén
Oslo Kodebureau
"Dennis Myrén" <de****@oslokb. no> wrote in message
news:fa******** **********@news 4.e.nsc.no...
You may utilize the features of System.Runtime. InteropServices .Marshal:

byte [] buff = new byte [Marshal.SizeOf( typeof(MYSTRUCT ))];
/* Put data into buffer here. */
IntPtr ptr = Marshal.AllocHG lobal(buff.Leng th);
Marshal.Copy(bu ff, 0x0, ptr, buff.Length);
MYSTRUCT myStruct = (MYSTRUCT) Marshal.PtrToSt ructure(ptr,
typeof(MYSTRUCT ));
Marshal.FreeHGl obal(ptr);
If you are OK with using "unsafe" code, i think this is the superior
version
(you will have to compile with the /unsafe switch):

MYSTRUCT myStruct;
byte [] buff = new byte [sizeof(MYSTRUCT )];
/* Put data into buffer here. */
unsafe
{
fixed (byte * pBuff = buff)
myStruct = * ((MYSTRUCT *) pBuff);
}
Remember to explicitly specify that the members of the struct must not
be organized in another way than in the order that they are defined.
This is done with the System.Runtime. InteropServices .StructLayoutAt tribute
attribute:

[ StructLayout( LayoutKind.Sequ ential, Pack = 0x1 ) ]
struct MYSTRUCT
{
...
}
--
Regards,
Dennis JD Myrén
Oslo Kodebureau
"Amil Hanish" <am********@hot mail.com> wrote in message
news:uJ******** *****@TK2MSFTNG P10.phx.gbl...
I have a huge byte array from another API that contains structs of
differing
sizes. I'd like to create n structs based on data in the byte array.
But
how? For example, if I want to take bytes 40-56 and create struct Foo
from
them...how do I do this? You can assume I know how to create the
properly
aligned struct.

Thanks

Amil


Nov 16 '05 #5
Hi,

"Amil Hanish" <am********@hot mail.com> wrote in message
news:uJ******** *****@TK2MSFTNG P10.phx.gbl...
I have a huge byte array from another API that contains structs of
differing
sizes. I'd like to create n structs based on data in the byte array. But
how? For example, if I want to take bytes 40-56 and create struct Foo
from
them...how do I do this? You can assume I know how to create the properly
aligned struct.
Here is a (another) way to do it without unsafe code :

// yourdata
byte[] data = ....;

// pin the byte array
GCHandle hData = GCHandle.Alloc( data, GCHandleType.Pi nned );

// get an address into the byte array
IntPtr pData = Marshal.UnsafeA ddrOfPinnedArra yElement( data,
YourStartIdxHer e );

// marshal/copy the unmanaged struct to a managed one
YourStruct ys = (YourStruct) Marshal.PtrToSt ruct( pData,
typeof(YourStru ct) );

// free pinning
hData.Free();

// ys can be used


The length is determined by the (unmanaged) size of the struct.
HTH,
greetings

Thanks

Amil

Nov 16 '05 #6

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

Similar topics

3
11029
by: Graham Nicholls | last post by:
Hi, I'm trying to size a jpeg file. The file size is held in a short (2 byte integer) at a certain offset. Once I've found these two bytes (they're in MSB,LSB order), I need to convert them to an integer - now I know that in C I'd just cast a pointer to the offset to a short, and that python doesn't cast, so how can I extract the value from...
7
52445
by: Prabhu | last post by:
Hi, I have to send a structure through TCPClient socket. we can send only byte array through the socket, So please any one can help me by telling How to convert a struct object into an byte array.. Thanks & Regards Prakash Prabhu
2
12165
by: Mel WEaver | last post by:
Hello, I have the following delphi structure for a binary file. I'm looking for idea how to read this file. Mel type TMenuDataStruct = packed record exename : string;
9
12676
by: Charles Law | last post by:
Suppose I have a structure Private Structure MyStruct Dim el1 As Byte Dim el2 As Int16 Dim el3 As Byte End Structure I want to convert this into a byte array where
7
6240
by: shellon | last post by:
Hi all: I want to convert the float number to sortable integer, like the function float2rawInt() in java, but I don't know the internal expression of float, appreciate your help!
6
4454
by: =?Utf-8?B?UHVjY2E=?= | last post by:
Hi, I'm using VS2005, .net 2 and C# for windows application. I need to convert a IntPtr to a byte to be able to add a meetingBlob data to the meeting class object in Active Directory schema. I get a "unspecified error" if I tried to add the data before converting to a byte in "deNewContextObject.Properties.Add((object)blob.pData);". ...
7
7199
by: Mario M. Mueller | last post by:
Hi, I have a binary file containing 3 byte float values (big endian). How can I read them into python? The struct module does not work, since it expects 4 byte floats. Any hints? Mario
1
3715
by: Paul Jarvis | last post by:
I have a large structure, below is a simplistic version of my structure: public struct MeanMinMaxSd { public double mean; public double min; public double max; public double sd; }
4
22125
by: Mason | last post by:
I have tried and tried... I'd like to read in a binary file, convert it's 4 byte values into floats, and then save as a .txt file. This works from the command line (import struct); In : f = open("test2.pc0", "rb") In : tagData = f.read(4) In : tagData
0
7921
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
0
8118
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
0
7964
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
6278
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
1
5504
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 presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
5217
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 then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3636
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2107
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1208
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.