How do I convert a binary string to hex using C?

前端 未结 4 1177
暖寄归人
暖寄归人 2021-01-21 07:53

How do I convert an 8-bit binary string (e.g. \"10010011\") to hexadecimal using C?

4条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-21 08:11

    How about

    char *binary_str = "10010011";
    unsigned char hex_num = 0;
    
    for (int i = 0, char *p = binary_str; *p != '\0'; ++p, ++i)
    {
        if (*p == '1' )
        {
            hex_num |= (1 << i);
        }
    }
    

    and now you've got hex_num and you can do what you want with it. Note that you might want to verify the length of the input string or cap the loop at the number of bits in hex_num.

提交回复
热议问题