Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Problem inserting a 32-digit number into an array

I am trying to write a C program to store a 32-bit number into an Array.
For Example, the number: 11000001110010000000000000000000
In the array, arr[0] would be 1 as that is the first digit.

However I am unable to get the desired output. This is my code:

#include<stdio.h>
int main ()
{
    int binarynumber;
    int arr[32];
    printf("Enter A binary Number:\n");
    scanf("%d", &binarynumber);
    for (int i = 32; i >= 0; i--) 
    {
        arr[i] = binarynumber % 10;
        binarynumber /= 10;
    }
    printf("The first digit is %d", arr[0]);
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

First of all if you want user to input 11000001110010000000000000000000, then you can’t get that whole number in an integer. So, if the user enters 3251109888 (decimal of 11000001110010000000000000000000), then better to get the number as unsigned int. Also you need to convert it to binary in the loop using %2 and /2. The loop will run from 0 to 31, so that arr[0] contains the LSB. The code will look like this –

int main ()
{
    unsigned int number;
    int arr[32];
    printf("Enter A binary Number:\n");
    scanf("%u", &number);
    for (int i = 0; i < 32; i++) 
    {
        arr[i] = number % 2;
        number /= 2;
    }

    for (int i = 31; i >= 0; i--) {
        printf("%d", arr[i]);
    }
    printf("\n");

    return 0;
}

If you want the user to input as 11000001110010000000000000000000, you need to get that input as string and then convert it into the digit using loop. To do that you can use –

int main ()
    int arr[32];
    char number[33] = {};
    scanf("%32s", string); // This will scan max 32 characters

    for (int i = 0; i < 32; i++)
    {
        arr[i] = number[i] - '0';
    }

    for (int i = 31; i >= 0; i--) {
        printf("%d", arr[i]);
    }
    printf("\n");

    return 0;
}

You may want to validate whether the input contains only digit or not using isdigit() inside the loop

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading