Conversion Precision Error when converting IEE Hal

2019-08-12 15:27发布

I have some precision error during the conversion from 16 bit half precision floating point format to decimal. It is able to accurately convert certain numbers while at the same time not accurate for others.

The code was originally designed to be for a 32 bit single precision floating point to decimal conversion. Thus, I have tried editing it to fit 16 bit half precision floating point format. As a result, the final value obtained ended up being half the expected value.

Eg. Expected value would be 1800, the result would be 900.

Thus, I decided to add a * 2 to the final operation. I am unsure as to how to fix the current precision error that I have, and why the result is also half the expected value.

Below includes the code I have edited with the respective outcomes.

#include <stdio.h> 
//#include <bits/stdc++.h> 
#include <string>
#include <iostream>
#include <sstream>
#include <math.h>
#include <limits.h>
#include <bitset>
using namespace std;

// Convert the 16-bit binary encoding into hexadecimal
int Binary2Hex( std::string Binary )
{
    std::bitset<16> set(Binary);      
    int hex = set.to_ulong();

    return hex;
}

// Convert the 16-bit binary into the decimal
float GetFloat16( std::string Binary )
{
    int HexNumber = Binary2Hex( Binary );
    printf("Test: %d\n", HexNumber);

    bool negative  = !!(HexNumber & 0x8000);
    int  exponent  =   (HexNumber & 0xf800) >> 10;    
    int sign = negative ? -1 : 1;

    // Subtract 15 from the exponent
    exponent -= 15;

    // Convert the mantissa into decimal using the
    // last 10 bits
    int power = -1;
    float total = 0.0;
    for ( int i = 0; i < 10; i++ )
    {
        int c = Binary[ i + 6 ] - '0';
        total += (float) c * (float) pow( 2.0, power );
        power--;
    }
    total += 1.0;

    float value = sign * (float) pow( 2.0, exponent ) * total * 2;

 }


The 16 bit floating point value that I am using would be: 0101010100010011

Expected Outcome: 81.2 Actual Outcome: 81.1875

0条回答
登录 后发表回答