Hello I'm new to C and I'm trying to print a decimal number converted to binary in standard order and in reverse order. I made a two function that accepts a decimal number and fills a dynamically allocated array with the binary conversion. Then returns a pointer to the array. Yet when I go to print the array, regardless if the array was populated with for( i = 0; i < 32; i ) or for( i = 31; i >= 0; i--) the printed results are the same. ie.
1000 0000 0000 0000 0000 0000 0000 0000
1000 0000 0000 0000 0000 0000 0000 0000
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
int *binConverter(int decimal)
{
int i,k;
int* arr;
arr = (int*)malloc(32*sizeof(int));
printf("i=0\n");
for( i = 0; i < 32; i )
{
k = decimal >> i;
if (k & 1)
{
arr[i] = 1;
printf("%d",arr[i]);
}else
{
arr[i]=0;
printf("%d",arr[i]);
}
}
printf("\n");
return arr;
}
int *binConverters(int decimal)
{
int i,k;
int* arr;
printf("i=31\n");
arr = (int*)malloc(32*sizeof(int));
for( i = 31; i >= 0; i--)
{
k = decimal >> i;
if (k & 1)
{
arr[i] = 1;
printf("%d",arr[i]);
}else
{
arr[i]=0;
printf("%d",arr[i]);
}
}
printf("\n");
return arr;
}
void printBin(int *array){
int *ptr = array, i;
for( i = 0; i < 32; i )
{
if (i%4==0)
printf(" ");
printf("%d",ptr[i]);
}
printf("\n");
}
int main(int argc, char const *argv[])
{
if (argc != 2){
printf("INVALID ARGUMENT\n");
return 1;
}
int decimal = atoi(argv[1]);
int *ptr=binConverter(decimal);
int *ptr2=binConverters(decimal);
printBin(ptr);
printBin(ptr2);
return 0;
}
CodePudding user response:
You're not storing the arrays differently.
Both functions have exactly the same loop body. The only difference is that the elements of the array are populated front-to-back in one case and back-to-front in the other. You're still putting the same values in the same array elements.
In the version the reverses the order, you need to extract the bits in the opposite order that you store them. So if you read bit i
then you store it in index 32 - i - 1
. You could also do the opposite: read bit 32 - i - 1
and store it in index i
.
CodePudding user response:
SPOILER!! Here's the different approach to the same problem:
#include<stdio.h>
#include<stdlib.h>
int* binConverter(int decimal)
{
int n = decimal;
int* arr = calloc(32,sizeof(int));
int i=0;
while(n>0)
{
arr[i] = n % 2;
n /= 2;
i;
}
return arr;
}
void main()
{
int n;
scanf("%d", &n);
int* arr;
arr = binConverter(n);
for(int i=31; i>=0;i--)
{
printf("%d", arr[i]);
}
}