I have the following code to convert an integer into a binary representation for each integer from 0 to 15, thus I need 4-bit representation of an integer.
the code it works fine but the problem is the length of the binary is not correct, so when given 1 as int it returns 1 as output instead of 0001. for 2 it should return 0010 but instead, it returns 10.
How can I change this code so it returns the correct representation? Using printf %04d
is oki when printing the results, but just for printing because the actual value is still different.
I was trying to make another method that gets an integer convert it into a string and then depending on its length add 0 before it until the length is 4.
#include <stdio.h>
#include <stdlib.h>
int convert(int dec)
{
if (dec == 0)
{
//printf("Base c\n");
return 0;
}
else
{
//printf("Rec call\n");
return (dec % 2) + 10 * convert(dec / 2);
}
}
int main(int argc, char *argv[])
{
// argc is number of arguments given including a.out in command line
// argv is a list of string containing command line arguments
int v = atoi(argv[2]);
printf("the number is:%d \n", v);
int bin = 0;
if(v >= 0 && v <= 15){
printf("Correct input \n");
bin = convert(v);
printf("Binary is: %04d \n", bin);
printf("Binary is: %d \n", bin);
}
else{
printf("Inorrect input, number cant be accepted");
}
What I need this method to do: 1. given an integer 2. return 4-bit representation of this integer, not sure if it should be an int or string. 3. for example convert(2) should return 0010, 6 returns 110, and I want this to be 0110 and so on. the method convert was supposed to do that for me. I hope I am clear about what I what to happen.
this should return for:
1 0001
2 0010
3 0011
4 0100
5 0101
6 0110
and so on
15 1111