Hex Translation of a char Buffer to a hex char Buffer


Some time ago I wrote up a hex2bin and a bin2hex utility in this blog.  This is an example of my hint in the comments in that blog as I’ve seen quite a few rather hashed attempts and it is really dauntingly simple.  I didn’t think that I needed to write it!  Note there’s no real error checking here because it has not been written to fit a particular purpose, so be careful. Somewhat interestingly this code runs faster compiled by a C compiler as opposed to a C++ compiler.

/**
 * char_to_hex_buf
 *
 * Takes a char buffer (s) of length l and inserts the ascii representation
 * of the hex values into the provided hex char buffer (h) of length lx2+1
 * terminating the hex buffer with '\0' in the final position of h[l].
 *
 * h - preallocated char buffer of length lx2+1 to put the translated source
 *     buffer hex character contents into
 * s - source char buffer of length l containing the characters to return as
 *     a hex character string the '\0' character is not a terminator for the
 *     purposes of this string
 * l - length of the source string
 *
 * returns EXIT_SUCCESS no other return value makes sense
 */
int char_to_hex_buf(char *h, const size_t l, const char *s) {

	size_t c;

	for (c=0;c<l;c++)
		sprintf(&(h[c*2]),"%02X",(unsigned char)(s[c]));

	return EXIT_SUCCESS;
}
  1. No comments yet.

You must be logged in to post a comment.

  1. No trackbacks yet.