I am very new to the C language.
I will need a small program to convert int
to binary and the binary preferably stored in an array so that I can further break them apart for decoding purpose.
I have following:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int arr[20];
int dec = 40;
int i = 0, ArrLen;
if(dec > 0)
{
while(dec > 0)
{
arr[i] = dec % 2;
i++;
dec = dec / 2;
}
}
else
{
printf("Invalid Number");
}
}
From the code above, I can store the binary value in arr
.
But instead of getting the binary equivalent: 101000
, the array now is like {0, 0, 0, 1, 0, 1}
, which is the reversed of the correct answer.
So the question is, how to get an array in the correct order or possibly flip it?
I have one thing for sure, and that is the maximum array length will not exceed 8
elements.
This conversion will be used repeatedly. So I plan to put it in a function so I'd be able to call the function, pass in an integer, and then get the array as the return value. So another question is, is it feasible to get an array as the return value?