2

Need some help. So far i have figured out how to display the binary conversions of the inputted values, but i need some tips on how to add these binary values into an array in order to actually be able to work with the binary values. Is it possible to populate an array through a switch case? Like i did so in case '0'. For some reason when i print the value of binary[i] it returns 0, instead of 0000.

int main()
{

int i = 0;
char hexstring[] = "24020004";
int binary[8];


while(hexstring[i])
{
     switch(hexstring[i])
     {
         case '0': binary[i] = 0000; printf("%i", binary[i]); printf("0000"); break;
         case '1': printf("0001"); break;
         case '2': printf("0010"); break;
         case '3': printf("0011"); break;
         case '4': printf("0100"); break;
         .
         .
         .
         case 'f': printf("1111"); break;
         default:  printf("\nInvalid hexadecimal digit %c ", hexstring[i]);
    }
    i++;
}
return 0;

}

G. Mata
  • 25
  • 4
  • Whar abour `case '0': binary[i] = 0x0; break; case '1': binary[i] = 0x1; break; ...... case 'f': binary[i] = 0xf; break;` ? – nalzok Mar 19 '16 at 07:25
  • "..when i print the value of binary[i] it returns 0, instead of 0000" - `binary[i]` is a number (specifically, a signed integer) and numbers don't "have" leading zeroes. You can force `printf` to show them: `printf("%04d", binary[i]);`. But that does not mean they are 'stored' in the value itself. – Jongware Mar 19 '16 at 09:39

2 Answers2

3

When you write binary[i] = 0000 you are saying that you are assigning octal constant to binary[i] which is 0. All leading zeros are omitted. But the first zero indicates that the constant should be interpretend as octal one. Another example: int x = 000011 just means that x is assigned an octal value of 11 or decimal value of 9. That is how compiler understands constants.

When the value is stored in the memory it knows nothing about what base it was written from. All numbers are stored in binary representation as you know. However numbers may have many views in different bases. We are convenient to work with numbers in decimal view.

There are many specifiers for printf for integer to output some its representations, they are %u - decimal, %x - hex, %o - for octal. Unfortunately no option to output binary number representation. In order to output number in base2 one should manually calculate each binary digit (0 or 1) and print them in corresponding order.

Try using the following code to output binary number representation.

void printInBase2(int n) {
    if(n == 0) { printf("0"); return; }
    int b = 0;
    for(b = 0; n >> b + 1; b++);
    for(; b >= 0; b--)
        printf("%c", (n >> b) % 2 + '0');
}

To read a number from a hexadecimal representation which is stored in string you can do this:

unsigned int number;
char hexstring[] = "24020004";
sscanf(hexstring, "%x", &number);

In case you want to store binary digits in int binary[] array you can do similar thing you did with string

case '0': binary[4 * i + 3] = 0, binary[4 * i + 2] = 0, binary[4 * i + 1] = 0, binary[4 * i] = 0; break;
case '1': binary[4 * i + 3] = 0, binary[4 * i + 2] = 0, binary[4 * i + 1] = 0, binary[4 * i] = 1; break;
case '2': binary[4 * i + 3] = 0, binary[4 * i + 2] = 0, binary[4 * i + 1] = 1, binary[4 * i] = 0; break;
...
case 'f': binary[4 * i + 3] = 1, binary[4 * i + 2] = 1, binary[4 * i + 1] = 1, binary[4 * i] = 1; break;

This way you will store each binary digit separately. Note that you binary array should be 4 times longer than hexstring.

Ivan Gritsenko
  • 4,166
  • 2
  • 20
  • 34
0

There are a number of possible ways to approach this depending on how exactly you want to hold/represent the individual hex-values. You can hold each value in binary[x] and create your printed output (e.g. "0010") as you have approached the problem. To also create a variable that will hold the correct numeric value, you can build the value by shifting each hex-value by an appropriate amount. Here is one approach:

#include <stdio.h>

enum { NBYTES = 8, NBAD = 128 };

int main (int argc, char **argv) {

    int i = 0, j = 0, n = 0;
    char *hexstring = argc > 1 ? argv[1] : "24020004",
         nothex[NBAD] = "";
    unsigned int binary[NBYTES] = {0},
                 value = 0;

    while (j < NBYTES && hexstring[i]) /* validate j to prevent overflow */
    {
        char *fmt = j > 0 ? "-%s" : "\n%s";
        switch (hexstring[i])
        {
            case '0': binary[j] = 0b0000; printf (fmt, "0000"); break;
            case '1': binary[j] = 0b0001; printf (fmt, "0001"); break;
            case '2': binary[j] = 0b0010; printf (fmt, "0010"); break;
            case '3': binary[j] = 0b0011; printf (fmt, "0011"); break;
            case '4': binary[j] = 0b0100; printf (fmt, "0100"); break;
            case '5': binary[j] = 0b0101; printf (fmt, "0101"); break;
            case '6': binary[j] = 0b0110; printf (fmt, "0110"); break;
            case '7': binary[j] = 0b0111; printf (fmt, "0111"); break;
            case '8': binary[j] = 0b1000; printf (fmt, "1000"); break;
            case '9': binary[j] = 0b1001; printf (fmt, "1001"); break;
            case 'a': binary[j] = 0b1010; printf (fmt, "1010"); break;
            case 'b': binary[j] = 0b1011; printf (fmt, "1011"); break;
            case 'c': binary[j] = 0b1100; printf (fmt, "1100"); break;
            case 'd': binary[j] = 0b1101; printf (fmt, "1101"); break;
            case 'e': binary[j] = 0b1110; printf (fmt, "1110"); break;
            case 'f': binary[j] = 0b1111; printf (fmt, "1111"); break;
            default:  nothex[n] = hexstring[i];
                    n += n < NBAD - 1;
                    goto badval;
        }
        /* value - holding numeric value */
        value += ('0' <= hexstring[i] && hexstring[i] <= '9') ? 
                (hexstring[i] - '0') << ((NBYTES - 1 - j) * sizeof value) :
                (hexstring[i] - 'W') << ((NBYTES - 1 - j) * sizeof value);
        j++;
      badval:
        i++;
    }
    printf ("\n value : 0x%08x (%u)\n\n", value, value);
    for (i = 0; i < NBYTES; i++)
        printf (" binary[%d] : 0x%x\n", i, binary[i]);
    if (*nothex) {
        printf ("\nwarning: invalid hexadecimal digit(s) in input.\n");
        for (i = 0; i < n; i++) printf (" %c", nothex[i]);
    }
    putchar ('\n');

    return 0;
}

Example Use/Output

$ ./bin/hex2bin
0010-0100-0000-0010-0000-0000-0000-0100
 value : 0x24020004 (604110852)

 binary[0] : 0x2
 binary[1] : 0x4
 binary[2] : 0x0
 binary[3] : 0x2
 binary[4] : 0x0
 binary[5] : 0x0
 binary[6] : 0x0
 binary[7] : 0x4

$ ./bin/hex2bin "cafebabe"
1100-1010-1111-1110-1011-1010-1011-1110
 value : 0xcafebabe (3405691582)

 binary[0] : 0xc
 binary[1] : 0xa
 binary[2] : 0xf
 binary[3] : 0xe
 binary[4] : 0xb
 binary[5] : 0xa
 binary[6] : 0xb
 binary[7] : 0xe

$ ./bin/hex2bin "hi-cafe-babe-up"

1100-1010-1111-1110-1011-1010-1011-1110
 value : 0xcafebabe (3405691582)

 binary[0] : 0xc
 binary[1] : 0xa
 binary[2] : 0xf
 binary[3] : 0xe
 binary[4] : 0xb
 binary[5] : 0xa
 binary[6] : 0xb
 binary[7] : 0xe

warning: invalid hexadecimal digit(s) in input.
 h i - -

Look it over and let me know if this is what you had envisioned.

David C. Rankin
  • 81,885
  • 6
  • 58
  • 85