Hi,
I am writing a program that receives a binary data stream over serial. The size of the bytes I read fluctuates between 1 and 4 bytes.
I want to read the specified number of bytes, and return an UInt32 with the binary data. I have tested around with the "BitConverter.ToUInt32", but I do not get the results I want. If I, as a test, use "BitConverter.ToString", I see that the values are what I want.
I wanted the byte array, that reads the binary data from the serial port, to have size "n_bytes", but if I do that, I get that "Destination array is not long enough to copy all the items in the collection". Because of this, I set the byte array size to the largest number of bytes I expect to read, which is 4 bytes.
But when I only read e.g. 2 bytes, I figured I have to shift the value so that I remove the remaining zeroes in the data array.
I have also tested the values I receive without bit shifting, but they do not make sense. How come they make sense with the BitConverter.ToString, but not .ToUInt32 (I have made sure the value is indeed unsigned)?
Here is my routine that converts the data:
UInt32 GET_DATA(int n_bytes)
{
UInt32 retValue = 0;
byte[] data = new byte[4];
switch (n_bytes)
{
case 1:
comPort.Read(data, 0, n_bytes);
retValue = BitConverter.ToUInt32(data, 0) >> 24;
break;
case 2:
comPort.Read(data, 0, n_bytes);
retValue = BitConverter.ToUInt32(data, 0) >> 16;
break;
case 3:
comPort.Read(data, 0, n_bytes);
retValue = BitConverter.ToUInt32(data, 0) >> 8;
break;
case 4:
comPort.Read(data, 0, n_bytes);
retValue = BitConverter.ToUInt32(data, 0);
break;
default:
retValue = 0;
break;
}
return retValue;
}
regards
Cato