Search code examples
cpercentage32-bit16-bit

Convert a 32-bit number to 16-bit


I need to convert a number to a percentage of my DAC's max value (0x0FFF) so my code to do that would be like this:

double percent;
short pct;

percent = (0x0FFF * pct)/100;

but I need a 16-bit value to send to the DAC not a 32-bit one. What is the quickest way to convert it to a 16-bit number? Can I shift it in?


Solution

  • There is no need to use floating point for this:

    uint16_t val = 0x0fffU * pct / 100U; // convert 0..100 value to 0..4095