1
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.

Fixed length strings or structures in C#

and

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).

Community
  • 1
  • 1
Manjoor
  • 4,091
  • 10
  • 43
  • 67

2 Answers2

0

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
  • 2,972
  • 1
  • 22
  • 36
  • 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 Feb 26 '10 at 08:13
  • 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 Feb 26 '10 at 12:59
  • I need to covert not only short but LONG,DOUBLE etc.. also As per my specs If your system uses little-endian order, the data types which occupy more than one byte should be twiddled (byte reversed). – Manjoor Mar 03 '10 at 09:46
  • Yes, every basic type except 'char', 'byte' and 'array of chars' must be converted. – qehgt Mar 04 '10 at 16:32
-2

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
  • 4,091
  • 10
  • 43
  • 67