如何使用C将8位二进制字符串(例如“10010011”)转换为十六进制?
答案 0 :(得分:19)
#include <stdlib.h>
strtol("10010011", NULL, 2);
答案 1 :(得分:4)
类似的东西:
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);
答案 2 :(得分:1)
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
}
答案 3 :(得分:0)
怎么样
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);
}
}
现在你已经有了hex_num,你可以用它做你想做的事。请注意,您可能需要验证输入字符串的长度或将循环限制为hex_num中的位数。