C语言 如何使用 C 将二进制字符串转换为十六进制?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5307656/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 08:03:27  来源:igfitidea点击:

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

cbinaryhex

提问by chris

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

如何使用 C 将 8 位二进制字符串(例如“10010011”)转换为十六进制?

回答by Ben

#include <stdlib.h>

strtol("10010011", NULL, 2);

回答by CyberDem0n

Something like that:

类似的东西:

char *bin="10010011";
char *a = bin;
int num = 0;
do {
    int b = *a=='1'?1:0;
    num = (num<<1)|b;
    a++;
} while (*a);
printf("%X\n", num);

回答by ughoavgfhw

void binaryToHex(const char *inStr, char *outStr) {
    // outStr must be at least strlen(inStr)/4 + 1 bytes.
    static char hex[] = "0123456789ABCDEF";
    int len = strlen(inStr) / 4;
    int i = strlen(inStr) % 4;
    char current = 0;
    if(i) { // handle not multiple of 4
        while(i--) {
            current = (current << 1) + (*inStr - '0');
            inStr++;
        }
        *outStr = hex[current];
        ++outStr;
    }
    while(len--) {
        current = 0;
        for(i = 0; i < 4; ++i) {
            current = (current << 1) + (*inStr - '0');
            inStr++;
        }
        *outStr = hex[current];
        ++outStr;
    }
    *outStr = 0; // null byte
}

回答by Sean

How about

怎么样

char *binary_str = "10010011";
unsigned char hex_num = 0;

for (int i = 0, char *p = binary_str; *p != '##代码##'; ++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.

现在你有了 hex_num 并且你可以用它做你想做的事。请注意,您可能希望验证输入字符串的长度或将循环限制在 hex_num 中的位数。