Prevent Invalid Floating-Point Operation Exception?

I use Visual C ++ to load binary data into float, for example:

  double dValue;
  memcpy(&dValue, lpData, sizeof(dValue));

In normal cases, this will work correctly. However, in some rare cases where binary data is corrupted, it dValuewill be invalid and any further operations on it will throw an “Invalid floating-point operation” exception.

I check dValuein the debugger and it displays as -1.#QNAN00000000000.

To prevent the exception, I need to check dValueafter loading it from binary data. I am trying to use:

  if (_finite(dValue))
  {do some tasks…
  }

But still invalid dValuewill cause the function to _finiteraise an exception Float-point invalid operation. Although it _finite(dValue)will return 0 correctly, the exception will be highlighted in memory. Even if I free him. Too many allocate / deallocate will run out of system resources anyway.

Therefore, is there a way to determine the validity of a double meaning without any exceptions?

+4
source share
1 answer

I would expect it to std::isnando everything you need and do it most efficiently. If this is not the case for your implementation on your platform, but you feel comfortable believing that floating point numbers use the IEEE 754 format, it is easy to write these functions yourself.

inline constexpr bool
isnan(const std::uint32_t bits) noexcept
{
  constexpr std::uint32_t exponent = UINT32_C(0x7f800000);
  constexpr std::uint32_t mantissa = UINT32_C(0x007fffff);
  return ((bits & exponent) == exponent) && ((bits & mantissa) != 0);
}

inline constexpr bool
isnan(const std::uint64_t bits) noexcept
{
  constexpr std::uint64_t exponent = UINT64_C(0x7ff0000000000000);
  constexpr std::uint64_t mantissa = UINT64_C(0x000fffffffffffff);
  return ((bits & exponent) == exponent) && ((bits & mantissa) != 0);
}

isfinite , , (bits & exponent) != exponent. isnormal, , ((bits & exponent) != exponent) && ((bits & exponent) != 0)). , "" .

, . . fread , , , " " (), , memcpy .

+1

Source: https://habr.com/ru/post/1627090/


All Articles