0

I am trying to convert a string representation of a 32 bit binary number to a string representative of the hex value of that number in a function called hexConversion(). To do this, I am required to use only basic C programming (for loops, basic arrays) and bit shifting/masking. In this assignment, the binary representation used is one that is returned as an array from another function binaryConversion().

I do have an idea of how to convert the 4 bit values into their hex values, but I am confused on how to actually break up the 32 bit value into smaller and more workable 4 bit values.

For example, I might want to change 11111111111111111111111111111111 to 1111 1111 1111 1111 1111 1111 1111 1111 so that I might be able to work with each 1111 separately to convert each to F

d827
  • 79
  • 7
  • You say you need to convert a 32-bit integer, but it appears you have a _string_ of values, or some other array of 32 values, and _not_ a 32-bit integer. Please clarify. Maybe show the declaration of `hexConversion` so we can see what data types you're using. When you say convert to "a hex value", are you also talking about a string? – paddy Mar 05 '19 at 04:29
  • This needs clarification. You say 32 bit integer but you are showing the binary representation. You can convert it to hex with printf() if it's an actual integer. **printf("%x", val)** – Bob Shaffer Mar 05 '19 at 04:37
  • Yes, you are right, my bad. `binaryConversion()` gives me an _string_ of 32 values which is representative of a binary number, and with `hexConversion()` I hope to create a _string_ of values representing the hex value of the binary number. Sorry if I'm wording this poorly. – d827 Mar 05 '19 at 04:39

1 Answers1

0

"Basic C" but maybe not what you are looking for...

binaryConversion(const char *bits, char *buf, int len) {
    snprintf(buf, len, "%lx", strtol(bits, NULL, 2));
}

A more complex solution specifically using bitmasks and shifts may be something like this...

binaryConversion(const char *bits, char *buf, int len) {
    const char *xdig = "0123456789ABCDEF";
    long val = strtol(bits, NULL, 2);
    int i;
    for (i = 0; i < 8; ++i) {
        int nib = val & 0xf;
        if (len > i) buf[i] = xdig[nib];
        val = val << 4;
    }
}
Bob Shaffer
  • 635
  • 3
  • 13
  • Pretty classic [giving of fish](https://knowyourphrase.com/give-a-man-a-fish) happening here. – paddy Mar 05 '19 at 04:54