# Thread: arrays and converting decimal to binary

1. ## 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 << "     ";

}

}```

2. Well, this being C++ why don't we take advantage of the STL and what it has to offer us. There are a couple of approaches to this, however lets keep things simple for now and just use std::vector and std::bitset. We can save the other advantages for later:
Code:
```#include <iostream>
#include <vector>
#include <string>
#include <bitset>

int main(void){

//Used to store each element of bcd (4 bit representation of number)
std::vector<std::bitset<4>>bcd;
std::string input;

std::cout <<"Enter number to convert(0-255):";
std::cin >> input;

//go through each number in the string and convert to binary representation
for(int i=0;i<input.size();i++){
std::bitset<4>number(input[i]-'0');//e.g.,converts char '2' to integer 2
bcd.push_back(number); //add the binary representation to our vector
}
//print out bcd
for(int j=0;j<bcd.size();j++){
std::cout<<bcd[j].to_string()<<" ";
}

return(0);
}```