954,483 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Problem with leading zeros

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!

Exercitus
Newbie Poster
1 post since Sep 2010
Reputation Points: 10
Solved Threads: 0
 

That looks fine to me - doesn't this do what you want? http://programmingexamples.net/index.php?title=CPP/ZeroPad

daviddoria
Posting Virtuoso
1,996 posts since Feb 2008
Reputation Points: 437
Solved Threads: 204
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: