From 72868fdc3fcc9a82c5f98f60fe362686cb7ff099 Mon Sep 17 00:00:00 2001 From: Stefan Wahren Date: Mon, 10 Dec 2012 21:16:46 +0100 Subject: [PATCH] add a new helper function ( mbus_hex2bin ) to convert hex values into binary values --- mbus/mbus-protocol-aux.c | 48 ++++++++++++++++++++++++++++++++++++++++ mbus/mbus-protocol-aux.h | 12 ++++++++++ 2 files changed, 60 insertions(+) diff --git a/mbus/mbus-protocol-aux.c b/mbus/mbus-protocol-aux.c index f91d246..3708d1e 100755 --- a/mbus/mbus-protocol-aux.c +++ b/mbus/mbus-protocol-aux.c @@ -17,6 +17,7 @@ #include #include +#include #include #define MBUS_ERROR(...) fprintf (stderr, __VA_ARGS__) @@ -2152,3 +2153,50 @@ mbus_scan_2nd_address_range(mbus_handle * handle, int pos, char *addr_mask) free(mask); return 0; } + +//------------------------------------------------------------------------------ +// Convert a buffer with hex values into a buffer with binary values. +// - invalid character stops convertion +// - whitespaces will be ignored +//------------------------------------------------------------------------------ +size_t +mbus_hex2bin(u_char * dst, size_t dst_len, const u_char * src, size_t src_len) +{ + size_t i, result = 0; + unsigned long val; + u_char *ptr, *end, buf[3]; + + if (!src || !dst) + { + return 0; + } + + memset(buf, 0, sizeof(buf)); + memset(dst, 0, dst_len); + + for (i = 0; i+1 < src_len; i++) + { + // ignore whitespace + if (isspace(src[i])) + continue; + + buf[0] = src[i]; + buf[1] = src[++i]; + + end = buf; + ptr = end; + val = strtoul(ptr, (char **)&end, 16); + + // abort at non hex value + if (ptr == end) + break; + + // abort at end of buffer + if (result >= dst_len) + break; + + dst[result++] = (u_char) val; + } + + return result; +} diff --git a/mbus/mbus-protocol-aux.h b/mbus/mbus-protocol-aux.h index 02694d9..40d9fd4 100755 --- a/mbus/mbus-protocol-aux.h +++ b/mbus/mbus-protocol-aux.h @@ -433,4 +433,16 @@ char * mbus_frame_data_xml_normalized(mbus_frame_data *data); */ int mbus_scan_2nd_address_range(mbus_handle * handle, int pos, char *addr_mask); +/** + * Convert a buffer with hex values into a buffer with binary values. + * + * @param src_buff source buffer with hex values + * @param src_len byte count of source buffer + * @param dest_buff destination buffer with binary values + * @param dest_len byte count of destination buffer + * + * @return byte count of successful converted values + */ +size_t mbus_hex2bin(u_char * dst, size_t dst_len, const u_char * src, size_t src_len); + #endif // __MBUS_PROTOCOL_AUX_H__