jmhobbs

C++ Print Binary Function

A while back I used a function I found on the web to print off a binary representation of a number while I was working on a blowfish implementation in C++. I haven't finished the blowfish, but I made some changes to the binary function, and thought I'd post it since it is a handy thing to have.

Essentially all I did was set it so it grouped the digits by 4 and padded out the MSB set with 0's so they all line up.

void binary(int number,int count=0) {
  int remainder;
  
  count++;
  
  if(number <= 1) {
    while(count % 4 != 0) {
      cout << '0';
      count++;
    }
    cout << number;
    return;
  }
  
  remainder = number%2;
  binary(number >> 1, count);
  if(count % 4 == 0)
    cout << ' ';
  cout << remainder;
}

Here's an example program, and the results.

#include 

using namespace std;

void binary(int number,int count=0) {
...
}

int main () {
	binary(0);
	cout << endl;
	binary(0xFF);
	cout << endl;
	binary(9872);
	cout << endl;
}

jmhobbs@lizzy$ ./a.out
0000
1111 1111
0010 0110 1001 0000
jmhobbs@lizzy$