简体   繁体   中英

C++ to .NET : I need help with understanding C++ code to convert it to .NET

C++ code is :

unsigned short* ui=(unsigned short*)&buf[110];
            CountDev=ui[0];

buf is byte[] and CountDev is unsigned int

(BCB6 Compiler x86)

My try is : F#

...CountDev  = System.BitConverter.ToInt32( [| arrayRead.[110]; arrayRead.[111] |] , 0 )

C#

...CountDev  = System.BitConverter.ToInt32( [arrayRead[110]; arrayRead[111]] , 0 )

But seriously I can't be sure about it. Check my try and tell me if I am doing it wrong please.

You might be able to use:

  ... = System.BitConverter.ToUint16(arrayRead, 110);

But it does depend on big/little endian (the order of the bytes in the array).
You will need specifications for that or a good test case.

I would just do this to simply concatenate the two bytes and putting it into an int:

UInt32 CountDev = (UInt32)arrayRead[111] << 8 | (UInt32)arrayRead[110];

since you just need the least significant two byte, and int is 4 byte long (the most significant or sign bit is not touched), you can also use a signed int:

int CountDev = (int)arrayRead[111] << 8 | (int)arrayRead[110];

Edit :

Henk Holtermans solution is definitely the better choice as it uses the endianess of the current machine:

UInt32 CountDev = (UInt32)System.BitConverter.ToUint16(arrayRead, 110);

您需要使用System.BitConverter.ToUInt16而不是System.BitConverter.ToInt32

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM