Hello, I am trying to create a program where I can work with an array of char that contain either 0 or 1 representing a decimal number that the user enters.
Basically I need to convert a decimal number into binary and store it into a char array. I wrote this program but it is outputting something weird.
char binary(int number)
{
int temp = 0, c = 0;
char buffer;
if (number % 2 == 0)
{
temp = number / 2;
}
else
{
number = number - 1;
temp = number / 2;
}
if (temp % 2 == 0)
{
buffer = '0';
}
else
{
buffer = '1';
}
return buffer;
}
int main()
{
int num;
cin >> num;
while(num != 0)
{
cout << binary(num);
if (num % 2 == 0)
{
num = num / 2;
}
else
{
num = num - 1;
num = num / 2;
}
}
return 0;
}
Can someone help me out??