0

I am new to C and would like some help with a problem I have.

Lets say I have a String that contains a 32 bit pattern for example "10001100110100010101100111000000".

What I am stuck with is how do I create a hexadecimal number for the bit pattern in the string so that the number contains groups of 4 bits.

For example the hexadecimal representation I require for the string above would be 8CD159C0

Ryan Gibson
  • 283
  • 2
  • 3
  • 9

4 Answers4

2

You can convert the binary string to a number with strtoul(), using base 2:

char *bits = "10001100110100010101100111000000";
unsigned num = strtoul(bits, NULL, 2);

and then convert the number to a hexadecimal string with snprintf():

char hex[9];
snprintf(hex, sizeof(hex), "%08X", num);

printf("%s\n", hex);
// Output: 8CD159C0

(This assumes that unsigned int has at least 32 bits on your platform. Otherwise use unsigned long.)

Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
2

Yosi's almost got it. But it should really be an unsigned int.

char *bin="10001100110100010101100111000000";
unsigned int num = 0;
for (char *a = bin; *a; ++a)
    num = (num << 1) | (*a - '0');
printf("%X\n", num);
ooga
  • 15,423
  • 2
  • 20
  • 21
1

Try it:

char *bin="10001100110100010101100111000000";
char *a = bin;
int num = 0;
do {
    int b = *a=='1'?1:0;
    num = (num<<1)|b;
    a++;
} while (*a);
printf("%X\n", num);
Yosi
  • 59
  • 3
  • I forgot to add that I need to store the hexadecimal number as a string. How would I do That? Also could you explain the 5th and 6th lines please? – Ryan Gibson Jan 21 '14 at 23:15
0
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

//#define b2i(c) (c == '1' ? 1 : 0)
#define I(c) c - '0'

char table[2][2][2][2] = {
    '0','1','2','3','4','5','6','7',
    '8','9','A','B','C','D','E','F'
};

char *bin2hex(const char *binstr){
    size_t len = strlen(binstr);
    size_t r = len % 4;//len & 3
    size_t add_len = (4 - r) % 4;
    len += add_len;
    char *bin = malloc(len + 1);
    strncpy(bin, "0000", add_len);//Normalization
    strcpy(bin + add_len, binstr);
    size_t hex_len = len / 4;// len >> 2;
    char *hexstr = malloc(hex_len + 1);
    size_t b, h;
    for(h=b=0;b<len; b+=4){
        hexstr[h++] = table[I(bin[b])][I(bin[b+1])][I(bin[b+2])][I(bin[b+3])];
    }
    hexstr[h] = '\0';
    free(bin);
    return hexstr;
}

int main(void){
    const char *bin = "10001100110100010101100111000000";
    char *hex = bin2hex(bin);
    printf("%s\n", hex);//8CD159C0
    free(hex);
    return 0;
}
BLUEPIXY
  • 39,699
  • 7
  • 33
  • 70