From: Bert Vermeulen Date: Tue, 18 Nov 2014 00:15:41 +0000 (+0100) Subject: Add analog helper sr_analog_float_to_string(). X-Git-Tag: libsigrok-0.4.0~760 X-Git-Url: https://sigrok.org/gitweb/?p=libsigrok.git;a=commitdiff_plain;h=c2a25ebb8fbf992cdf9fee96d44f1c27f1f48f51 Add analog helper sr_analog_float_to_string(). --- diff --git a/include/libsigrok/proto.h b/include/libsigrok/proto.h index dfce6aa2..0f4b9884 100644 --- a/include/libsigrok/proto.h +++ b/include/libsigrok/proto.h @@ -30,6 +30,8 @@ SR_API int sr_analog_to_float(const struct sr_datafeed_analog2 *analog, float *buf); +SR_API int sr_analog_float_to_string(float value, int digits, char *outbuf, + int bufsize); /*--- backend.c -------------------------------------------------------------*/ diff --git a/src/analog.c b/src/analog.c index 9def3ac8..ccf6d319 100644 --- a/src/analog.c +++ b/src/analog.c @@ -17,7 +17,10 @@ * along with this program. If not, see . */ +#include +#include #include +#include #include "libsigrok.h" #include "libsigrok-internal.h" @@ -98,3 +101,36 @@ SR_API int sr_analog_to_float(const struct sr_datafeed_analog2 *analog, return SR_OK; } + +/* + * Convert a floating point value to a string, limited to the given + * number of decimal digits. + * + * @param value The value to convert. + * @param digits Number of digits after the decimal point to print. + * @param outbuf Buffer in which the resulting string will be placed. + * @param bufsize Size of the buffer in bytes. + * + * @retval SR_OK + * + * @since 0.4.0 + */ +SR_API int sr_analog_float_to_string(float value, int digits, char *outbuf, + int bufsize) +{ + int cnt, i; + + /* This produces at least one too many digits */ + snprintf(outbuf, bufsize, "%.*f", digits, value); + for (i = 0, cnt = 0; outbuf[i] && i < bufsize; i++) { + if (isdigit(outbuf[i++])) + cnt++; + if (cnt == digits) { + outbuf[i] = 0; + break; + } + } + + return SR_OK; +} +