Reputation: 1142
I'm parsing some packets that are sent using Bluetooth and I used the same code that I've used previously to parse TCP packets, somehow even if the byte array is received correctly, short values are different when parsed.
This is what PrintByteArray prints:
byte[] { 0, 1, 0, 4, 0, 0, 0, 1, 66, 112, 0, 1, ...}
PrintByteArray(data);
int commandType = (int)BitConverter.ToInt16(data, 0);
int payloadSize = (int)BitConverter.ToInt16(data, 2);
Debug.WriteLine(commandType); // prints 256 instead of 1
Debug.WriteLine(payloadSize); // prints 1024 instead of 4
I'm not sure what I'm doing wrong, everything looks fine.
Upvotes: 2
Views: 307
Reputation: 10411
BitConverter uses the machine's endianness (typically little endian for window). The data you are receiving is in big endian. You can use IPAddress.NetworkToHostOrder to read the data correctly.
Here is your code with a helper to convert from Big Endian to Little Endian.
PrintByteArray(data);
int commandType = (int)BigToLittleEndian(BitConverter.ToInt16(data, 0));
int payloadSize = (int)BigToLittleEndian(BitConverter.ToInt16(data, 2));
Debug.WriteLine(commandType); // prints 256 instead of 1
Debug.WriteLine(payloadSize); // prints 1024 instead of 4
static short BigToLittleEndian(short value)
{
return BitConverter.IsLittleEndian ? System.Net.IPAddress.NetworkToHostOrder(value) : value;
}
Upvotes: 2
Reputation: 150108
It looks like the byte array you are receiving is encoded Big Endian rather than Little Endian.
If you swap the byte order to {1, 0, 4, 0, ...} you will get the results you expect when parsing the data.
The BitConverter class supports converting arrays of bytes to various types and supports data that originiates with either Endianness.
Upvotes: 1