I need to convert a two byte array to SFloat format according to IEEE-11073.
How can I do that?
I answer my question here.
public float ToSFloat(byte[] value)
{
if (value.Length != 2)
throw new ArgumentException();
byte b0 = value[0];
byte b1 = value[1];
var mantissa = unsignedToSigned(ToInt(b0) + ((ToInt(b1) & 0x0F) << 8), 12);
var exponent = unsignedToSigned(ToInt(b1) >> 4, 4);
return (float)(mantissa * Math.Pow(10, exponent));
}
public int ToInt(byte value)
{
return value & 0xFF;
}
private int unsignedToSigned(int unsigned, int size)
{
if ((unsigned & (1 << size-1)) != 0)
{
unsigned = -1 * ((1 << size-1) - (unsigned & ((1 << size-1) - 1)));
}
return unsigned;
}
Loosely based on the C implementation by Signove on GitHub I have created this function in C#:
This function assumes that the bytes are in little endian format. If not you will have to swap
bytes[0]andbytes[1]in the first line of the function. Or perhaps even better remove the first line from the function and change the function argument to accept aUInt16(the IEEE 11073 value) and then let the caller decide how to extract this value from the input.I highly advise you to test this code because I do not have any test values to verify the correctnes of the conversion.