user3192998
user3192998

Reputation: 25

How to convert byte array to int32

Please help me to convert byte array in to int32 using c#.

I used the following code but did not get the exact value

byte[] newArray3 = new[] { buffer[m+2], buffer[m+3], buffer[m], buffer[m+1] }; 
int t = BitConverter.ToInt32(newArray3,0);

Thanks in advance.

      *15 14 13 12 11 10 9 8* * 7 6 5 4 3 2 1 0**

Word1 ...S msb ....buffer[m+1].. . .........buffer[m].................

word2 .....buffer[m+3]............................buffer[m+2]......... lsb

Upvotes: 2

Views: 291

Answers (2)

Luaan
Luaan

Reputation: 63772

Unless you need to change the MSB position, use

BitConverter.ToInt32(buffer, m);

There's no need to copy the data to another byte array in-between.

If you do need to change the endianness, you're stuck with using bitshifting as LB2 suggested above.

Upvotes: 2

LB2
LB2

Reputation: 4860

use bitshifting instead

m[0] << 24 || m[1] << 16 || m[2] << 8 || m[3]

assumes m[0] contains MSB...

Upvotes: 4

Related Questions