Convert uint32_t to double between 0 and 1 [closed]

8

I have a shamefully naive question: What is the best way to convert a uint32_t to a double between 0 and 1?

My naive way is

double myconvert(uint32_t a)
{
    double n = static_cast<double>(std::numeric_limits<uint32_t>::max() - std::numeric_limits<uint32_t>::min());
    return static_cast<double>(a) / n;
}

But I was wondering if there is a better way?

Share
Improve this question
10
  • 1
    Perhaps I'm old-fashioned, but I find mathematical code with static_cast<double> hard to read. I prefer to promote implicitly all the coefficients in a term using 1.0 at the start. – Bathsheba Apr 20 at 15:12
  • 1
    Hmm. Naïve and old-fashioned ... that's pushing it a bit. :-) – Adrian Mole Apr 20 at 15:31
  • i don't understand the purpose. so you are casting uint32 input into a double then dividing it by 0x41EFFFFFFFE00000 which is the max uint32 cast to a double. – user_number153 Apr 20 at 16:02
  • 3
    Note that neither of the casts in the code in the question is needed. – Pete Becker Apr 20 at 16:04
  • 2
    What do you consider better, in objective terms? – TylerH 12 hours ago

Comments

Popular posts from this blog

Meaning of `{}` for return expression

Get current scroll position of ScrollView in React Native

flutter websocket connection issue