Wednesday, July 11, 2012

Write a program to convert decimal number to binary string

The approach:-
  1. Initialize a string array to hold the output binary string.

  2. mod the input number by 2.  If reminder is '1' include '1' in the output string. Else include '0'.

  3. Divide the number by 2 for next iteration.

  4. Repeat steps 2 and 3 till number becomes 0.

  5. Reverse the string to get the output sequence.

C++ program to convert decimal number to binary string

#include <iostream>
#include <cstring>
#include <cstdlib>
#include <cmath>
using namespace std;

char* dec2bin(int n) {
 char* str = (char*)malloc(sizeof(32));
 char bin_str[] = { '0', '1' };

 int count = 0;
 while ( n > 0 ) {
  int rem = n % 2;
  n = n / 2;
  rem ? str[count] = bin_str[1] : str[count] = bin_str[0];
  count++;
 }
 str[count] = '\0';

 // reverse the string
 int size = strlen(str) - 1;
 for ( int i = 0; i <= size/2; i++ ) {
  char ch = str[i];
  str[i] = str[size - i];
  str[size - i] = ch;
 }

 return str;
}

int main() {
 int n = 100;
 cout << dec2bin(n) << endl;
}

Output:-
1100100

1 comment :

  1. rem ? str[count] = bin_str[1] : str[count] = bin_str[0];

    can be expressed as

    str[count] = bin_str[rem];

    ReplyDelete

Contact Form

Name

Email *

Message *

Back to Top