Converting two bytes to an IEEE-11073 16-bit SFLOAT in C#

2.8k Views Asked by At

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;
    }
2

There are 2 best solutions below

0
Martin Liversage On BEST ANSWER

Loosely based on the C implementation by Signove on GitHub I have created this function in C#:

Dictionary<Int32, Single> reservedValues = new Dictionary<Int32, Single> {
  { 0x07FE, Single.PositiveInfinity },
  { 0x07FF, Single.NaN },
  { 0x0800, Single.NaN },
  { 0x0801, Single.NaN },
  { 0x0802, Single.NegativeInfinity }
};

Single Ieee11073ToSingle(Byte[] bytes) {
  var ieee11073 = (UInt16) (bytes[0] + 0x100*bytes[1]);
  var mantissa = ieee11073 & 0x0FFF;
  if (reservedValues.ContainsKey(mantissa))
    return reservedValues[mantissa];
  if (mantissa >= 0x0800)
    mantissa = -(0x1000 - mantissa);
  var exponent = ieee11073 >> 12;
  if (exponent >= 0x08)
    exponent = -(0x10 - exponent);
  var magnitude = Math.Pow(10d, exponent);
  return (Single) (mantissa*magnitude);
}

This function assumes that the bytes are in little endian format. If not you will have to swap bytes[0] and bytes[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 a UInt16 (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.

0
Jovirus On
   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;
}