T
T
timkin12018-09-12 19:56:36
C++ / C#
timkin1, 2018-09-12 19:56:36

Can a number be represented as a float?

Hello!
How can you check whether an unsigned number is a float?
Thanks in advance!

Answer the question

In order to leave comments, you need to log in

2 answer(s)
J
jcmvbkbc, 2018-09-12
@jcmvbkbc

representability of an unsigned number as a float

Whole? Standard type (int/long/...) or just sequences of digits?
The simplest option:
bool is_representable_as_float(unsigned v)
{
    return v == (unsigned)(float)v;
}

M
Mercury13, 2018-09-13
@Mercury13

Float contains 23 bits of the mantissa and an implicit one. The float order is outrageous, and even qword won't hit it.
This means that anything further than 23 bits from the upper one must be zero.

bool isPreciseFloat(unsigned long long n)
{
  // Простейшая проверка: стираем нижние 24 бита
  // Если в них вписываемся — ДА.
  unsigned long long n1 = n & ~((1ULL << 24) - 1);
  if (n1 == 0)
    return true;

  // Получаем верхнюю единицу
  // (можно также двоичным поиском, но я этого с листа не напишу)
  while (true) {
    unsigned long long n2 = n1 & (n1 - 1);
    if (n2 == 0)
      break;
    n1 = n2;
  }

  // Получаем маску всего, что ниже 23 бит от верхнего бита.
  n1 >>= 23;
  --n1;

  // Проверяем по маске
  return (n & n1) == 0;
}

Wrote "from the sheet", there may be errors.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question