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?
You can parameterize the array by using a pointer to int. It may be useful to parameterize the number of digits as well.
void int_to_bin_digit(unsigned int in, int count, int* out)
{
/* assert: count <= sizeof(int)*CHAR_BIT */
unsigned int mask = 1U << (count-1);
int i;
for (i = 0; i < count; i++) {
out[i] = (in & mask) ? 1 : 0;
in <<= 1;
}
}
int main(int argc, char* argv[])
{
int digit[8];
int_to_bin_digit(40, 8, digit);
return 0;
}
or recursive V2.0:
#include <stdio.h>
char *binaryToAbits(unsigned int answer, char *result) {
if(answer==0) return result;
else {
result=binaryToAbits(answer>>1,result);
*result='0'+(answer & 0x01);
return result+1;
}
}
int main(void) {
unsigned int numToConvert=0x1234ABCD;
char ascResult[64];
*binaryToAbits(numToConvert,ascResult)='\0';
printf("%s",ascResult);
return 0;
}
Note, thanks to @chux, here is a better recursive function that handles the case of converting 0 - it outputs "0" instead of "":
char *binaryToAbits(unsigned int answer, char *result) {
if(answer>1) {
result=binaryToAbits(answer>>1,result);
}
*result='0'+(answer & 0x01);
return result+1;
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With