How do I convert an 8-bit binary string (e.g. "10010011") to hexadecimal using C?
Asked
Active
Viewed 4.1k times
4
-
2Looks basically the same as [converting-binary-to-hexadecimal](http://stackoverflow.com/questions/2672776/converting-binary-to-hexadecimal) – MAK Mar 15 '11 at 04:59
-
@MAK they are not the same as it mentioned "string" and "C" programming language – alphakevin Sep 09 '13 at 20:23
4 Answers
4
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);

CyberDem0n
- 14,545
- 1
- 34
- 24
-
that worked great! however, I need to return it as an unsigned char value...when I convert "11010011", it returns fffffd3. how do I just return it as d3? here is my code unsigned char string_to_hex(char * neighbors) { char *a = neighbors; int num = 0; do { int b = *a=='1'?1:0; num = (num = num<<1)|b; a++; } while(*a); return ('%x', num); } – chris Mar 15 '11 at 05:13
-
Use an unsigned char rather than an int. Also use "%02X" for the format specifier. – Sean Mar 15 '11 at 05:18
-
-
@self. It *could* result in UB if `num` is right shifted more than `sizeof(int)*CHAR_BIT - 1` times or the resulting mathematical value can't be represented by `num`. Neither happens here, so no UB. In general, shifting signed numbers could easily result in UB, if not done correctly. But not always UB. Using unsigned would save trouble in most cases though ;-) – P.P May 14 '14 at 22:41
-
@BlueMoon You're right, standard agrees, I still wouldn't do it. In the meantime you can read and upvote my question :-) http://stackoverflow.com/questions/23582544/strict-aliasing-and-memory-locations – this May 15 '14 at 00:16
2
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
}

ughoavgfhw
- 39,734
- 6
- 101
- 123
1
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.

Sean
- 5,290
- 2
- 24
- 21