开发者

How to convert binary to hexadecimal string in C/glib?

开发者 https://www.devze.com 2023-04-06 14:59 出处:网络
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

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 开发者_如何学Golibraries for this. Could someone point me in the right direction, please?


Something like this?

void print_hex(const char * buffer, size_t size)
{
    for (size_t i = 0; i < size; i++)
        printf("%02x", buffer[i]);
}


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;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号