Home > Mobile >  How to check data redundancy on float32 variable in C?
How to check data redundancy on float32 variable in C?

Time:09-06

I would like to check data corruption of a variable in some function. In general, if it is a unsigned integer variable i can easily check like below method

sender side:

uint8 actual_data = 23;
uint8 send_data = ~actual_data; /*bitwise NOT*/
send_data_to_other(send_data, actual_data);

receiver side:

void receive_data_to_other(uint8 received_data, uint8 actual_data)
{
   uint8 check_data = ~received_data;
   if(check_data == actual_data)
   {
     printf("data is correct");
   }
   else
   {
     printf("something wrong")
   }
}

But suppose if i am using float32 data,

eg: float32 actual_data = 23.22f;

then i can not perform bitwise NOT(~) for float32 variables. Any one Suggest me how can we check the data verification for float32 variable in C?

CodePudding user response:

Assuming sizeof (float) == sizeof (uint32_t):

    uint32_t data;
    uint32_t ndata;

    memcpy(&data, &f, sizeof(data));
    ndata = ~data;

But of course, your send function will need to send larger chunks of data.

To "reconstruct" float you will need to copy data in the opposite direction.

float toFloat(uint32_t data)
{
    float f;

    memcpy(&f, &data, sizeof(f));
    return f;
}

Do not worry about memcpy overhead as this function is very well known to the compiler and optimizing compilers will optimize out the call.

CodePudding user response:

The binary representation of floating point numbers uses scientific notation instead of normal binary.

See this https://www.doc.ic.ac.uk/~eedwards/compsys/float/

  • Related