How do I convert an 8-bit binary string (e.g. \"10010011\") to hexadecimal using C?
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
}