From 57a54f824c460d224ab451893863df0fddda5111 Mon Sep 17 00:00:00 2001 From: Jef Driesen Date: Mon, 28 Dec 2015 14:24:40 +0100 Subject: [PATCH] Add helper functions for converting hexadecimal data. --- examples/common.c | 36 ++++++++++++++++++++++++++++++++++++ examples/common.h | 3 +++ 2 files changed, 39 insertions(+) diff --git a/examples/common.c b/examples/common.c index ee552cd..fb7f73e 100644 --- a/examples/common.c +++ b/examples/common.c @@ -232,6 +232,42 @@ dctool_descriptor_search (dc_descriptor_t **out, const char *name, dc_family_t f return DC_STATUS_SUCCESS; } +static unsigned char +hex2dec (unsigned char value) +{ + if (value >= '0' && value <= '9') + return value - '0'; + else if (value >= 'A' && value <= 'F') + return value - 'A' + 10; + else if (value >= 'a' && value <= 'f') + return value - 'a' + 10; + else + return 0; +} + +dc_buffer_t * +dctool_convert_hex2bin (const char *str) +{ + // Get the length of the fingerprint data. + size_t nbytes = (str ? strlen (str) / 2 : 0); + if (nbytes == 0) + return NULL; + + // Allocate a memory buffer. + dc_buffer_t *buffer = dc_buffer_new (nbytes); + + // Convert the hexadecimal string. + for (unsigned int i = 0; i < nbytes; ++i) { + unsigned char msn = hex2dec (str[i * 2 + 0]); + unsigned char lsn = hex2dec (str[i * 2 + 1]); + unsigned char byte = (msn << 4) + lsn; + + dc_buffer_append (buffer, &byte, 1); + } + + return buffer; +} + void dctool_file_write (const char *filename, dc_buffer_t *buffer) { diff --git a/examples/common.h b/examples/common.h index 55dbb91..f17d578 100644 --- a/examples/common.h +++ b/examples/common.h @@ -45,6 +45,9 @@ dctool_event_cb (dc_device_t *device, dc_event_type_t event, const void *data, v dc_status_t dctool_descriptor_search (dc_descriptor_t **out, const char *name, dc_family_t family, unsigned int model); +dc_buffer_t * +dctool_convert_hex2bin (const char *str); + void dctool_file_write (const char *filename, dc_buffer_t *buffer);