How do I convert an 8-bit binary string (e.g. "10010011") to hexadecimal using C?
-
2Looks basically the same as converting-binary-to-hexadecimalMAK– MAK2011-03-15 04:59:14 +00:00Commented Mar 15, 2011 at 4:59
-
@MAK they are not the same as it mentioned "string" and "C" programming languagealphakevin– alphakevin2013-09-09 20:23:10 +00:00Commented Sep 9, 2013 at 20:23
Add a comment
|
4 Answers
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);
5 Comments
chris
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); }
Sean
Use an unsigned char rather than an int. Also use "%02X" for the format specifier.
this
Shifting signed integer is undefined in c.
P.P
@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 ;-)this
@BlueMoon You're right, standard agrees, I still wouldn't do it. In the meantime you can read and upvote my question :-) stackoverflow.com/questions/23582544/…
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
}
Comments
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.