Home > Software design >  Problem inserting a 32-digit number into an array
Problem inserting a 32-digit number into an array

Time:11-14

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]);
}

CodePudding user response:

I guess bitwise operations should do the job

#include<stdio.h>
int main ()
{
    int binarynumber;
    int arr[32];
    printf("Enter A binary Number:\n");
    scanf("%d", &binarynumber);
    for (int i = 0, j = sizeof(arr) - 1; i < sizeof(arr); i  , j--) 
    {
        int binarynumber_copy = binarynumber;
        // shifting number `j` bits right and cutting off one bit by bitwise AND
        arr[i] = (binarynumber_copy >> j) & 1;
    }
    printf("The first digit is %d", arr[0]);
}

CodePudding user response:

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("2s", 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

CodePudding user response:

If I were you, I'd read it as a string and iterate through each character and added (and converted) them to the int array. As mentioned, typing the 32 digit long number is too big to store inside an int.

  •  Tags:  
  • c
  • Related