binary - Any precision loss when converting float64 to uint64 in C? assuming only the whole number part of the data is meaningful -
i have counter field 1 tcp protocol keeps track of samples sent out. defined float64. need translate protocol different one, in counter defined uint64.
can safely store float64 value in uint64 without losing precision on whole number part of data? assuming fractional part can ignored.
edit: sorry if didn't describe clearly. there no code. i'm looking @ 2 different protocol documentations see if 1 can translated other.
please treat float64 double, documentation isn't written , pretty old.
many thanks.
i assuming asking 64 bit floating point values such ieee binary64 documented in https://en.wikipedia.org/wiki/double-precision_floating-point_format .
converting double
represented 64 bit ieee floating point value uint64_t
not lose precision on integral part of value, long value non negative , less 264. if value larger 253, representation double
not allow complete precision, whatever computation led value inaccurate anyway.
note reverse false, ieee floats have less precision 64 bit uint64_t
, close different large values convert same double
values.
note counter implemented 64 bit double
intrinsically limited precision of floating point type. incrementing value larger 253 1 have no effect @ all. using floating point type implement packet counter seems bad idea. using uint64_t
counter directly seem safer bet. have worry wrap around @ 264, condition can check in unlikely case expect count far.
if cannot change format, verify floating point value within range conversion , store appropriate value if not:
#include <stdint.h> ... double v = get_64bit_value(); uint64_t result; if (v < 0) { result = 0; } else if (v >= (double)uint64_max) { result = uint64_max; } else { result = (uint64_t)v; }
Comments
Post a Comment