Hexadecimal values division in C

Viewed 758

I have two numbers represented in a hexadecimal format:

uint16_t NUM   = 0xEEEE;  // Numerator
uint16_t DENUM = 0XFFFF;  // Denominator

I want to have the numeric value of the division. Let us declare a double here:

double divisonResult = (double)(NUM / DENUM); // Shall be 0.9333333333333333

When I debug, the value of divisonResult is always 0.

In my case, is casting allowed or not?

Is there another way to get the wanted result?

1 Answers

The notation is a red herring: the problem is that the cast happens after the integer division due to your enclosing that operation in parentheses.

Use simply

(double)NUM / DENUM

although I prefer

1.0 * NUM / DENUM

not only for clarity but in case NUM is ever changed to a wider type than a double whereupon a cast could cause truncation.

Related