Extract binary to hex string conversion

This commit is contained in:
Romain Vimont 2024-02-25 14:54:17 +01:00
parent c92a554453
commit ea96552751
4 changed files with 34 additions and 9 deletions

View File

@ -12,4 +12,7 @@ struct sc_hid_event {
uint8_t size;
};
char *
sc_hid_event_to_string(const struct sc_hid_event *event, size_t max_data_bytes);
#endif

View File

@ -5,6 +5,7 @@
#include "aoa_hid.h"
#include "util/log.h"
#include "util/str.h"
// See <https://source.android.com/devices/accessories/aoa2#hid-support>.
#define ACCESSORY_REGISTER_HID 54
@ -20,17 +21,12 @@ static void
sc_hid_event_log(uint16_t accessory_id, const struct sc_hid_event *event) {
// HID Event: [00] FF FF FF FF...
assert(event->size);
unsigned buffer_size = event->size * 3 + 1;
char *buffer = malloc(buffer_size);
if (!buffer) {
LOG_OOM();
char *hex = sc_str_to_hex_string(event->data, event->size);
if (!hex) {
return;
}
for (unsigned i = 0; i < event->size; ++i) {
snprintf(buffer + i * 3, 4, " %02x", event->data[i]);
}
LOGV("HID Event: [%d]%s", accessory_id, buffer);
free(buffer);
LOGV("HID Event: [%d] %s", accessory_id, hex);
free(hex);
}
bool

View File

@ -3,6 +3,7 @@
#include <assert.h>
#include <errno.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
@ -333,3 +334,22 @@ sc_str_remove_trailing_cr(char *s, size_t len) {
}
return len;
}
char *
sc_str_to_hex_string(const uint8_t *data, size_t size) {
size_t buffer_size = size * 3 + 1;
char *buffer = malloc(buffer_size);
if (!buffer) {
LOG_OOM();
return NULL;
}
for (size_t i = 0; i < size; ++i) {
snprintf(buffer + i * 3, 4, "%02X ", data[i]);
}
// Remove the final space
buffer[size * 3] = '\0';
return buffer;
}

View File

@ -138,4 +138,10 @@ sc_str_index_of_column(const char *s, unsigned col, const char *seps);
size_t
sc_str_remove_trailing_cr(char *s, size_t len);
/**
* Convert binary data to hexadecimal string
*/
char *
sc_str_to_hex_string(const uint8_t *data, size_t len);
#endif