decimal to binary

Dec 31, 2013 at 6:57am
This code gives result as binary of the array values written eg: {15,127,7} the output was 11111111111111, can anyone help to modify this to get an output with fixed binary number irrespective of the number given. that means whatever value smaller value i am typing for 127 i should get output with 7 bit .
#include <iostream>
#include<vector>
using namespace std;
int main()
{
long binary_number ;
vector <int> binary;
int decimals[3]={15,127,7};

while ( decimals[2] >= 1 )
{
binary_number =decimals[2] % 2;
decimals[2] /= 2;
binary.push_back(binary_number);

}

for ( int i = (int) binary.size()-1; i >= 0; i-- )
//cout << binary[i] << "";


while ( decimals[1] >= 1 )
{
binary_number =decimals[1] % 2;
decimals[1] /= 2;
binary.push_back(binary_number);

}

for ( int i = (int) binary.size()-1; i >= 0; i-- )

while ( decimals[0] >= 1 )
{
binary_number =decimals[0] % 2;
decimals[0] /= 2;
binary.push_back(binary_number);

}

for ( int i = (int) binary.size()-1; i >= 0; i-- )
cout << binary[i] << "";
return 0;

}

Dec 31, 2013 at 8:00am
You could set the formatted output to pad with '0' with a width of 8.
Dec 31, 2013 at 8:27am
You could use LB's method with std::setfill1 and std::setw2 from the iomanip3 library

Or even use a std::bitset4 with the number of bits you want it to be. Then when you output use tostring5 method if you want it in binary otherwise use the toulong6 or toullong7 (long long) methods for decimal.

1 http://www.cplusplus.com/reference/iomanip/setfill/?kw=setfill
2 http://www.cplusplus.com/reference/iomanip/setw/
3 http://www.cplusplus.com/reference/iomanip/
4 http://www.cplusplus.com/reference/bitset/bitset/?kw=bitset
5 http://www.cplusplus.com/reference/bitset/bitset/to_string/
6 http://www.cplusplus.com/reference/bitset/bitset/to_ulong/
7 http://www.cplusplus.com/reference/bitset/bitset/to_ullong/

[edit]You could also use the fill constructor of std::vector and assign the fill to 0 and the size to be the number of bits you want it to be.
http://www.cplusplus.com/reference/vector/vector/vector/
cplusplus dot com wrote:
fill (2)
explicit vector (size_type n);
vector (size_type n, const value_type& val,
const allocator_type& alloc = allocator_type());
so say you want it to be an 8 bit (1 byte) it would look like std::vector<int> vec( 8 , 0 );[/edit]
Last edited on Dec 31, 2013 at 8:34am
Dec 31, 2013 at 9:55am
thank you LB & giblit
Topic archived. No new replies allowed.