Skip to content

Instantly share code, notes, and snippets.

@bojanpotocnik
Last active June 17, 2020 11:21
Show Gist options
  • Save bojanpotocnik/d2b6e3f6a139cf9c58fb88e8b4aee56c to your computer and use it in GitHub Desktop.
Save bojanpotocnik/d2b6e3f6a139cf9c58fb88e8b4aee56c to your computer and use it in GitHub Desktop.
Function to get hex string representation of a buffer
/** Get "xx xx xx ..." string representation of the buffer - returned string MUST BE free()-d after use! */
static char * hexlify(const void * buffer, size_t len)
{
const uint8_t * p_buffer = (uint8_t *) buffer;
const size_t str_len = p_buffer ? len * 3 : sizeof("<null>");
char * const str = malloc(str_len);
if (!str) {
LOGE("Could not allocate %d bytes", (int) str_len);
return NULL;
}
char *p_str = str;
if (p_buffer) {
while (len-- > 0) {
const uint8_t val = *(p_buffer++);
int_fast8_t nbl;
for (nbl = 1; nbl >= 0; nbl--) {
const uint8_t nbl_val = ((nbl > 0) ? (val >> 4) : val) & 0x0F;
*(p_str++) = (nbl_val < 10 ? '0' : 'a' - 10) + nbl_val;
}
*(p_str++) = ' ';
}
if (p_str > str) {
*(p_str - 1) = '\0'; /*< Overwrite last ' ' with null terminator */
}
else {
*p_str = '\0'; /*< Nothing was done (len was 0) */
}
}
else {
strcpy(str, "<null>");
}
return str;
}
/**
* Wrapper wrapping @ref hexlify around statements, free-ing the string afterwards
*
* Wrapper content is only executed if hex string is successfully generated.
*
* @param obj_[in] Object to print - pointer to this object `&(obj_)` will be used for hexlify input.
* @param len_[in] Number of bytes to print - if negative then `sizeof(obj_)` will be used instead.
* @param statements_[in] Statements to execute after calling hexlify and before free-ing the generated string, only
* if hexlify did not return NULL.
* Two new variables are defined in scope of this wrapper and can be used in the statements:
* - const int len Number of bytes to print (either `len_` or `sizeof(obj_)`).
* - char *s Generated hex string representation.
*/
#define hexlify_wrap(obj_, len_, statements_) \
do { \
const int len = ((int) (len_)) < 0 ? (int) sizeof(obj_) : (int) (len_); \
char *s = hexlify(&(obj_), (size_t) len); \
if (s) { \
statements_; \
free(s); \
} \
} while (0)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment