23ewt 3tqa
23ewt 3tqa

Reputation: 21

Converting from decimal to binary number system using strings

I need help trying to fix the second part of my program, converting decimal to binary, this is what I have so far and when i compile it i keep getting 0 so im not sure what i did wrong. any help please?

#include <stdio.h>
#include <string.h>
#include <math.h>

int main()
{

    char string[100];
    int s;
    char a;   
    char j;
    int sum = 0;
    int r;
    int q;

    printf("B = B to D\n");
    printf("D = D to B\n");
    printf("choose which one to convert to:");
    scanf("%c%c", &a, &j);

    if (a == 'B') 
    {
        printf("enter binary number to convert to decimal: ");
        scanf("%s", string);

        for(s = strlen(string)-1; s >= 0; s--)
        {

            if(string[s] == '1')
            {
                sum = sum + pow(2, strlen(string) - (s +1));
            }
        }
        printf("the decimal number is: %d\n", sum);
    }

    if (a == 'D')
    {
        printf("enter decimal number to convert to binary: ");
        scanf("%s", string);

        while (r > 0)
        {
            r = q%2;
            q = q%2;
        } 

        printf("the binary number is: %d\n", r);

    }

    return 0;
}

Upvotes: 0

Views: 1444

Answers (3)

Some programmer dude
Some programmer dude

Reputation: 409176

The simplest thing is probably to convert the string input to a proper integer (using e.g. strtol), and the convert that number to a string containing only ones and zeroes.

Something like:

/* Convert a (possibly signed) decimal number in a string to a long integer */
unsigned long number = (unsigned long) strtol(string, NULL, 10);

char output_string[65];  /* If longs are 64 bits, plus one for terminator */
char *output_ptr = output_string;

/* Start with the highest bit, go down to the lowest */
/* sizeof(long) is either 4 or 8 depending on 32 or 64 bit platforms */
/* Multiply with 8 to get the number of bits */
/* -1 because bits are numbered from 0 to 31 (or 63) */
for (int bit = (sizeof(unsigned long) * 8) - 1; bit >= 0; bit--)
{
    /* Using right shift to get the current bit into the lowest position */
    /* Doing bitwise AND to see if the lowest bit is a one or a zero */
    /* Adding '0' makes a a printable ASCII value of a digit */
    *output_ptr++ = ((number >> bit) & 1) + '0';

    /* `*output_ptr` gets the value that `output_ptr` points to */
    /* Then use the `++` operator to increase the pointer */
    /* Now `output_ptr` points to the next character in `output_string` */
}

/* Terminate string */
*output_ptr = '\0';

printf("%ld in binary is %s\n", number, output_string);

Upvotes: 1

Jonathan Leffler
Jonathan Leffler

Reputation: 753805

This C99 code will do the trick if you want a negative number to be printed as a string of binary digits with a sign:

if (a == 'D')
{
    int r;
    printf("enter decimal number to convert to binary: ");
    scanf("%d", &r);
    int i = 0;
    int p = (r >= 0) ? (r = -r, 1) : 0;
    string[i++] = '\0';

    do
    {
        string[i++] = (r % 2) == 0 ? '0' : '1';
        r /= 2;
    } while (r != 0);
    if (!p)
        string[i++] = '-';

    int k = 0;
    while (--i > k)
    {
        char t = string[i];
        string[i] = string[k];
        string[k++] = t;
    }

    printf("the binary number is: %s\n", string);
}

For example, given -1234 (decimal), the output is -10011010010 (binary). It also handles both the extremes: INT_MAX, -INT_MAX and INT_MIN (assuming 32-bit int):

B = B to D
D = D to B
choose which one to convert to: D
enter decimal number to convert to binary: 2147483647
the binary number is: 1111111111111111111111111111111

B = B to D
D = D to B
choose which one to convert to: D
enter decimal number to convert to binary: -2147483647
the binary number is: -1111111111111111111111111111111

B = B to D
D = D to B
choose which one to convert to: D
enter decimal number to convert to binary: -2147483648
the binary number is: -10000000000000000000000000000000

If, on the other hand, you want the bit pattern corresponding to the value, then Joachim Pileborg's answer does that for you.

(It's C99 code because it declares variables at convenient points part way through a block, rather than at the start of a block as C89 requires.)

Upvotes: 1

David
David

Reputation: 1419

There are a few problems here. For one thing, the first time that you check r, it is uninitialized. Another problem is that you're setting both r and q to the same value every time you go through the while loop. You probably want q = q/2 instead of q = q%2. Finally, you're overwriting r every pass through the loop, instead of building up a string of bits. Here's some pseudocode for what you want to do:

 output_string = ""

 while input > 0:
     output_string = concat(input%2, output_string)
     input /= 2

 print output_string

Note that you're also never converting the string you read in to an integer and putting that in q, so you'll need to do that as well.

Upvotes: 1

Related Questions