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

喜你入骨 提交于 2019-12-11 06:13:12

问题


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?


回答1:


Something like this?

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



回答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;
}


来源:https://stackoverflow.com/questions/7519084/how-to-convert-binary-to-hexadecimal-string-in-c-glib

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!