Is there a common way or good public domain code for converting binary (i.e. byte array or memory block) to hexadecimal string? I have a several applications that handle encryption keys and checksums and I need to use this function a lot. I written my own "quick and dirty" solution for this but it only works with binary objects of fixed size and I'm looking for something more universal. It seems pretty mundane task and I'm sure there should be some code or libraries for this. Could someone point me in the right direction, please?
Asked
Active
Viewed 2,680 times
1
-
sorry for my previous wrong answer. Have a look here: http://stackoverflow.com/questions/2482211/c-converting-binary-to-decimal – Heisenbug Sep 22 '11 at 17:53
-
It is not the same. By binary I mean a block of memory, not binary string. Basically I'm looking for same functionality of what hexdump does on Linux. – dtoux Sep 22 '11 at 18:02
2 Answers
2
Something like this?
void print_hex(const char * buffer, size_t size)
{
for (size_t i = 0; i < size; i++)
printf("%02x", buffer[i]);
}

harald
- 5,976
- 1
- 24
- 41
-
Yep, this looks right. Let me give it a try. Essentially I want the function to return a string, but this is a good starting point. Thanks. – dtoux Sep 22 '11 at 18:03
-
By using sprintf, strcat and friends it should be trivial to expand this to output to a string buffer. Good luck! – harald Sep 22 '11 at 18:18
-
GLib has `g_strdup_printf()` which allocates a properly sized string buffer for you. Might be useful. – ptomato Sep 22 '11 at 19:36
-
That's true, however since data data block is of variable size and so will be the output string, I will likely allocate the memory myself and then just use `g_sprintf()` to fill it up. The code should be trivial. Thanks for the help everyone. – dtoux Sep 22 '11 at 22:29
2
Thanks everybody for your help. Here is how final code turned out in glib notation:
gchar *
print_to_hex (gpointer buffer, gsize buffer_length) {
gpointer ret = g_malloc (buffer_length * 2 + 1);
gsize i;
for (i = 0; i < buffer_length; i++) {
g_snprintf ((gchar *) (ret + i * 2), 3, "%02x", (guint) (*((guint8 *) (buffer + i))));
}
return ret;
}

dtoux
- 1,754
- 3
- 21
- 38
-
Why use the less portable glib functions and types? There's nothing here that could not be done using standard C. – harald Sep 23 '11 at 16:37
-
@harald: I understand your point and it is totally valid. The short answer is - for consistency. This function will go into a utility library and most of other functions are glib specific, so our policy for such cases is to use only glib types through the entire library. – dtoux Sep 23 '11 at 23:20
-