# Binary representation of numbers...

• 05-14-2003
roc
Binary representation of numbers...
Hello everyone. I am trying to write a program in C++ and I need to represent a series of numbers in binary form. I need numbers as big as 1,000,000 and I was wondering if C++ has some sort of function to change base 10 numbers into binary numbers?

Thanks for the help in advance!
• 05-14-2003
DougDbug
bitset
bitset is part of the Standard Template Library. You can use bitset for displaying numbers in binary. For input, you can use strtoul()

Here's a program I wrote a few months ago that "converts" between bases.
• 05-14-2003
major_small
I created a program that converts ASCII characters into integers (base 10) and binary (base 2) numbers... it won't help you much, except for maybe the binary function... I was just playing around with recursion on this program...

Code:

```/*         Letter => Number => Binary         This Program will take an ASCII character and convert it into a number, then         convert it into Binary. The user may enter a single charater, or a string of         any length, seeing as the program uses a loop to convert it one charater at a         time.  The output is put into a file so it can easily be copied/pasted. The         file is overwritten every time the program runs.                 Major_Small */ #include <iostream.h> #include <fstream.h> int power(int),binary(int&,int); void main() {         char cha;         int i,ch,cho;         ofstream ofile("letnumbin.log",ios::trunc);         cout<<"Press Enter after you entered a string or ASCII\n"                 <<"character to find The Decimal and Binary equivalent:\n\n";         while(cin.get(cha))         {                 if(cha!='\n')                 {                         ch=int(cha);                         cho=ch;        // assigns number to be sent to output file                         cout<<cha<<'\t'<<ch<<'\t';                         ofile<<cha<<'\t'<<ch<<'\t';                         for(i=0;i<9;i++)                         {                                 cout<<binary(ch,i);                // destroys int ch to 0 - cant be used ofile                                 ofile<<binary(cho,i);        // uses special assigned number                         }                         cout<<endl;         ofile<<endl;                 }         }         cout<<endl; } int binary(int& ch,int i) {         if(ch>=power(8-i))         {                 ch-=power(8-i);                 return 1;         }         else           return 0; } int power(int exponent) {         if(exponent>0)                 return(2*power(exponent-1));         else                 return 1; }```