I need to convert a byte array to a UInt16 (ushort) array. I am able to do so from a byte array to a UInt32 array.
I already looked at this SO question. But I cannot use BitConverter or the solution given in the referenced question.
I also referred to these questions as well: THIS and THIS.
This is what I have tried so far.
for (uint objIndex = 0; objIndex < data.Length; ++objIndex)
{
data[objIndex] = (Convert.ToUInt16(byteArray[objIndex * sizeof(UInt16) + 0].ToString()) << 8)
+ byteArray[objIndex * sizeof(UInt16) + 1];
// Error - Cannot implicitly convert type 'int' to 'ushort'. An explicit conversion exists.
data[objIndex] = ((ushort)(byteArray[objIndex * sizeof(UInt16) + 0]) << 8)
+ byteArray[objIndex + 1];
// Error - Cannot implicitly convert type 'int' to 'ushort'. An explicit conversion exists.
}
Please let me know what is missing here.
EDIT: I was able to fix it after casting each of the number to an ushort as shown below.
for (ushort objIndex = 0; objIndex < data.Length; ++objIndex)
{
ushort length = sizeof(UInt16);
data[objIndex] = (ushort)( (ushort)(byteArray[objIndex * length] << (ushort)8) +
byteArray[objIndex + 1] );
}
data[objIndex] = (ushort) (((ushort)(byteArray[objIndex * sizeof(UInt16) + 0]) << 8) + byteArray[objIndex + 1]; )
– Favus