Hello,

I have a program assignment that is supposed to that converts decimal numbers to binary, hexadecimal, and BCD. I am having an issue with keep the leading zeros on the binary. I have used a recursive function to output a binary conversion.

#include <iostream>
#include <iomanip>
using namespace std;

const int MAX=255;
void binary(int);

int main (){
	int number;
	number=0;
	cout<<"DECIMAL       BINARY       HEXADECIMAL       BCD"<<endl;
	for (int i=0;i<=MAX;i++){

	cout<<number<<"       ";
	if (number<=9){
		cout<<"  "; }
	else if (number>9&&number<=99){
	cout<<" "; }

	binary(number);
	
	number++;
	cout<<endl;
	}
	system ("pause");
	return 0;
}


void binary(int number){
int r;

if (number<=0){
	cout<<number;
	return;
}
 r=number%2;
 binary(number>>1);
 cout<<r;
}

The output should look like:
DECIMAL _______ BINARY
0 _____________ 00000000
1 _____________ 00000001
2 _____________ 00000010
. _____________ .
. _____________ .
255 ___________ 11111111

However it shows as:
DECIMAL _______ BINARY
0 _____________ 0
1 _____________ 1
2 _____________ 10
. _____________ .
. _____________ .
255 ___________ 11111111

NOTE: The underscores represent a space and the forum eliminates unnecessary white space

I tried using

setfill('0')<<setw(8)

within the function but that adds zeros after each digit rather then the whole number. Is there a way to use these manipulators on the function as a whole like

binary(number).setfill('0').setw(8)

? Or is this completely off base?

Thanks In Advance!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.