Search code examples
carduinoavr-gcc

Guarantees of data preservation between int32_t and float?


I'm reading through the supplied code for a demo board(specifically the DC21561A) and found this snippet of code:

int32_t min_current_threshold_code;                                                                                                                                                                                                          
min_current_threshold_code = (min_current_threshold / LTC2946_DELTA_SENSE_lsb) * resistor;                                                                                                                                                   
ack |= LTC2946_write_16_bits(LTC2946_I2C_ADDRESS, LTC2946_MIN_DELTA_SENSE_THRESHOLD_MSB_REG, (min_current_threshold_code << 4));

Here, everything on the RHS of first assignment is a float. From what I can tell, and have tested, an assignment with LHS int32_t and RHS float the decimal bits of the float will be discarded and only the integer is left; i.e. '1.5 * 3.5 = 5'.

The data above is written to a register over I2C. I assume the floats are used to give a more accurate estimate of threshold values. However, I was wondering if this truncation when assigning a float to an int32_t is required by the C(or C++) standard or something compiler specific?

Edit** Some people have asked for more code. While my question is answered, here's the rest for thoroughness.

At the top of the file there is

float min_current_threshold = read_float();

const float LTC2946_DELTA_SENSE_lsb = 2.5006105E-05;

const float resistor = .02;


Solution

  • Yes, the standards mandates the truncation, for example in C99 chapter 6.3.1.4 paragraph 1:

    When a finite value of real floating type is converted to an integer type other than _Bool, the fractional part is discarded (i.e., the value is truncated toward zero).