Learn Computer Science programming - C# and C++ Algorithms

 
Convert a number to Binary

Convert a number to a binary form without using any special CBIN functions

Pseudocode
string BinaryString (int Num)
{
  Result = "";
  while (Num <> 0) {
    if Odd (Num)
         Result = '1' + Result;
    else
         Result = '0' + Result;
    Num = Num / 2;
  }
}
Code
tobinary.zip
File Size: 3198 kb
File Type: zip
Download File

#include <iostream>
#include <string.h>
#include <windows.h>
using namespace std;

char *ToBinary (int x, char result[])
{
char binaryString[16];
ZeroMemory(binaryString,16);

while (x)
{
if ((x&1) == 1)
strcat (binaryString, "1");
else
strcat (binaryString, "0");
x=x/2;
}


strcpy(result,binaryString);
// Flip String
int Start = 0;
int End = strlen(result) -1;
while (Start < End)
{
char Temp = result[Start];
result[Start++] = result[End];
result[End--] = Temp;
}
return  result;
}

void main()
{
int x;
wcout <<  endl << "*** Convert 276 To Binary ***" << endl;
wcout << "*************************************************" << endl;
char binary[16];
ZeroMemory(binary,16);
ToBinary(276,binary);
cout << "Binary Number for 276 is: " << binary;
cin >> x;
 }