Skip to content

Commit cdcb33b

Browse files
mike-scottioannisg
authored andcommitted
net: lwm2m: plain text: fix float formatting
Formatting a float32/64 value for plain text is broken. Example for 32bit: val1=0 and val2=500000 is equivalent to 0.5 Current formatter was using %d.%d (%lld.%lld for 64bit) so exported value was 0.500000 (or 0.5) To fix this, for val2 use a zero-padded formatter for the maximum length of each bit length (6 for 32bit and 9 for 64bit), and then remove the zero characters at the end of the string. Notes re: handling of val1/val2 signs: - eliminate potential negative sign when converting val2 to avoid: a value like: 0.-5 - use negative val2 when val1 is 0 to fix small negative handling such as -0.5 Fixes: #16154 Signed-off-by: Michael Scott <[email protected]>
1 parent 7c2f063 commit cdcb33b

File tree

1 file changed

+38
-4
lines changed

1 file changed

+38
-4
lines changed

subsys/net/lib/lwm2m/lwm2m_rw_plain_text.c

Lines changed: 38 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -125,16 +125,50 @@ static size_t put_float32fix(struct lwm2m_output_context *out,
125125
struct lwm2m_obj_path *path,
126126
float32_value_t *value)
127127
{
128-
return plain_text_put_format(out, "%d.%d",
129-
value->val1, value->val2);
128+
size_t len;
129+
char buf[sizeof("000000")];
130+
131+
/* value of 123 -> "000123" -- ignore sign */
132+
len = snprintf(buf, sizeof(buf), "%06d", abs(value->val2));
133+
if (len != 6U) {
134+
strcpy(buf, "0");
135+
} else {
136+
/* clear ending zeroes, but leave 1 if needed */
137+
while (len > 1U && buf[len - 1] == '0') {
138+
buf[--len] = '\0';
139+
}
140+
}
141+
142+
return plain_text_put_format(out, "%s%d.%s",
143+
/* handle negative val2 when val1 is 0 */
144+
(value->val1 == 0 && value->val2 < 0) ?
145+
"-" : "",
146+
value->val1, buf);
130147
}
131148

132149
static size_t put_float64fix(struct lwm2m_output_context *out,
133150
struct lwm2m_obj_path *path,
134151
float64_value_t *value)
135152
{
136-
return plain_text_put_format(out, "%lld.%lld",
137-
value->val1, value->val2);
153+
size_t len;
154+
char buf[sizeof("000000000")];
155+
156+
/* value of 123 -> "000000123" -- ignore sign */
157+
len = snprintf(buf, sizeof(buf), "%09lld", abs(value->val2));
158+
if (len != 9U) {
159+
strcpy(buf, "0");
160+
} else {
161+
/* clear ending zeroes, but leave 1 if needed */
162+
while (len > 1U && buf[len - 1] == '0') {
163+
buf[--len] = '\0';
164+
}
165+
}
166+
167+
return plain_text_put_format(out, "%s%lld.%s",
168+
/* handle negative val2 when val1 is 0 */
169+
(value->val1 == 0 && value->val2 < 0) ?
170+
"-" : "",
171+
value->val1, buf);
138172
}
139173

140174
static size_t put_string(struct lwm2m_output_context *out,

0 commit comments

Comments
 (0)