chris
chris

Reputation: 83

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

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

Upvotes: 3

Views: 44926

Answers (4)

Ben
Ben

Reputation: 1359

#include <stdlib.h>

strtol("10010011", NULL, 2);

Upvotes: 22

ughoavgfhw
ughoavgfhw

Reputation: 39925

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
}

Upvotes: 2

Sean
Sean

Reputation: 5490

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.

Upvotes: 1

CyberDem0n
CyberDem0n

Reputation: 15056

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);

Upvotes: 4

Related Questions