views:

325

answers:

2
Struct {
 byte F1[2]
 SHORT F2
 byte F3[512]
} BPD


CBD
{
 SHORT CLENGTH
 byte DATA[]
}

Above are 2 c++ structure. Here SHORT is of 2 byte signed. What would be the best way to convert it into C#?

(Note that in 2nd struture length of DATA is uundefined.)

I have seen following two links.

http://stackoverflow.com/questions/415214/fixed-length-strings-or-structures-in-c

and

http://stackoverflow.com/questions/2871/reading-a-c-c-data-structure-in-c-from-a-byte-array

After reading data into structure i need to covert the short variable to big endian. (reversing bytes).

A: 

Only 'short' is needed to be converted. Array of bytes identical on big/little endian platform.

So, just read structures and do something like this:

data.F2 = ((uint)data.F2 >> 8) | ( ((uint)data.F2 & 0xFF) << 8);

and

data.CLENGTH = ((uint)data.CLENGTH >> 8) | ( ((uint)data.CLENGTH & 0xFF) << 8);

qehgt
Thanks for the response. My first questiion is stll there. The best way to extract data from a byte array. Converting it into structure? Putting byte data into a class constructor and processing it into class?I have more than 100 structure to handle and these are nested upto 10 level.
Manjoor
For the first structure - yes, 'C# value type' is an optimal.For second structure, it's better to replace it to one dynamic array.
qehgt
can you show me how?
Manjoor
I need to covert not only short but LONG,DOUBLE etc.. alsoAs per my specsIf your system uses little-endian order, the data types which occupy more than one byte should be twiddled (byte reversed).
Manjoor
Yes, every basic type except 'char', 'byte' and 'array of chars' must be converted.
qehgt
A: 

Solved myself.

Structures are good but if you are not going to modify any data classes are better to use. I have create classes in c# for c++ structure and for big to little endian conversion i have create 3 library functions and it works for me.

Thnaks everybody for the valuable input.

Manjoor
Care to share your code?
Pat