2

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

2
  • Similar question: Efficient way to read big endian data in C# Commented Feb 20, 2014 at 16:47
  • What are the values in buffer[m] through buffer[m+3], and what do you expect the returned value to be? Commented Feb 20, 2014 at 17:28

2 Answers 2

4

use bitshifting instead

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

assumes m[0] contains MSB...

Sign up to request clarification or add additional context in comments.

Comments

2

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.

1 Comment

@CodesInChaos You can always check if the hardware is the endianness you want and only use the manual bit ORing if it doesn't suit your needs.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.