Skip to content

Commit 1d969d8

Browse files
committed
pmbus: fix scaling possible bug
The scaling logic can be incorrect. When exp5 >= 0, the condition (1 << (-exp5)) attempts a left shift with a negative value, which is undefined behavior. The logic should be inverted: when exp5 is negative, use (1 << (-exp5)), and when positive, use division. The simplest option is to use math.h's ldexp(). It seems it does not require libm.
1 parent 442669a commit 1d969d8

File tree

1 file changed

+5
-5
lines changed

1 file changed

+5
-5
lines changed

src/pmbus_io.c

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
#include <fcntl.h>
99
#include <unistd.h>
1010
#include <errno.h>
11+
#include <math.h>
1112

1213
int
1314
pmbus_open(const char *dev, int addr7) {
@@ -97,15 +98,14 @@ pmbus_lin11_to_double(uint16_t raw) {
9798
if (mant & 0x400)
9899
mant |= ~0x7FF;
99100

100-
double scale = (exp >= 0) ? (1 << exp) : 1.0 / (1 << (-exp));
101-
102-
return (double)(mant * scale);
101+
/* value = mantissa * 2^exp */
102+
return ldexp((double)mant, exp);
103103
}
104104

105105
double
106106
pmbus_lin16u_to_double(uint16_t raw, int exp5) {
107-
double scale = (exp5 >= 0) ? (1 << exp5) : 1.0 / (1 << (-exp5));
108-
return (double)(raw * scale);
107+
/* value = raw * 2^exp5 */
108+
return ldexp((double)raw, exp5);
109109
}
110110

111111
uint16_t

0 commit comments

Comments
 (0)