arrays and converting decimal to binary
hey, I am writing a small program that takes a decimal number ranging from 1 to 255 and converts it to bcd. Somewhere near the end of the program my output gets messed up. For example I need 255 to be converted to 0010 0101 0101.
Code:
#include <iostream>
using namespace std;
int main()
{
int l = 0;
int i = 0;
int k = 0;
int p = 0;
int num = 255;
int newValue = 0;
int remainder = 0;
int bin[12];
int sec[5];
newValue = num;
if(num <= 9) // these first if statements are meant to store 255 into 3
{ // separate array slots
}
else if(num <100 && num > 9)
{
bin[k] = num/10;
p = num%10;
k++;
bin[k]=p/1;
k++;
}
else
{
bin[k] = num/100;
p = num%100;
k++;
bin[k]=p/10;
p = p%10;
k++;
bin[k] = p;
k++;
cout << bin[0];
cout << bin[1];
cout << bin[2]<< " ";
}
k = 0;
while(k !=3) // this begins the code which converts the digits into each binary
{ //number
newValue = bin[k];
cout << bin[k] << " this is the bin"<<endl;
k++;
while(newValue >= 1)
{
remainder = newValue%2;
if (remainder == 0) //sends the value into the correct if statement.
{
sec[i] = 0;
i++;
}
else
{
sec[i]= 1;
i++;
}
newValue = newValue/2;
}
for(i; i<4; i++) // fills empty slots with 0's to follow the format
{
sec[i]= 0;
}
for (i = 3; i >= 0; i--) // prints out the data
{
cout << sec[i];
}
cout << " ";
}
}