Perform the conversion from a float decimal number to single precision (4 byte) IEEE 754 format number?
-
Could anyone explain for me what these code doing? Could give me an example ? thanks typedef union ieee_754_single_precision { BYTE bytes[FLOAT_BYTES]; float value; IEEE_SBITS bits; } SIEEE_754; void cHARTTransmitter::Float2IEEE(float fDecimalNum, BYTE *pbIEEE) { SIEEE_754 local; short j = FLOAT_BYTES - 1; local.value = fDecimalNum; for (i = 0 ; i < FLOAT_BYTES; i++) { pbIEEE[i] = local.bytes[j--]; } } Float2IEEE((float)m_data, Data);
-
Could anyone explain for me what these code doing? Could give me an example ? thanks typedef union ieee_754_single_precision { BYTE bytes[FLOAT_BYTES]; float value; IEEE_SBITS bits; } SIEEE_754; void cHARTTransmitter::Float2IEEE(float fDecimalNum, BYTE *pbIEEE) { SIEEE_754 local; short j = FLOAT_BYTES - 1; local.value = fDecimalNum; for (i = 0 ; i < FLOAT_BYTES; i++) { pbIEEE[i] = local.bytes[j--]; } } Float2IEEE((float)m_data, Data);
It's converting a float from little-endian form (presuming this code is running on an x86/x64 PC) to big-endian. Let me add comments to your code:
// Declare a union so we can easily access the bytes of a float
typedef union ieee_754_single_precision
{
BYTE bytes[FLOAT_BYTES]; // Let's hope FLOAT_BYTES == sizeof(float)
float value;
IEEE_SBITS bits; // Don't know what this is...
} SIEEE_754;void cHARTTransmitter::Float2IEEE(float fDecimalNum, BYTE *pbIEEE)
{
SIEEE_754 local;
// Set up an index to iterate through the bytes array in local - see my later comment.
short j = FLOAT_BYTES - 1;
// Assign the float to the union. The bytes making up the float are now available though local.bytes
local.value = fDecimalNum;// Now transfer the bytes from local to pbIEEE, reversing their order
// as we do so. It might make it clearer if we replace "j--" by "(FLOAT_BYTES-1)-i"
// If we look at i and j, we see that
//
// pbIEEE[0] = local.bytes[3];
// pbIEEE[1] = local.bytes[2];
// pbIEEE[2] = local.bytes[1];
// pbIEEE[3] = local.bytes[0];
//
// (BTW - what compiler is this that doesn't require i to be declared?!)
for (i = 0 ; i < FLOAT_BYTES; i++)
{
pbIEEE[i] = local.bytes[j--];
}
}Java, Basic, who cares - it's all a bunch of tree-hugging hippy cr*p