• ### Announcements

#### Archived

This topic is now archived and is closed to further replies.

# decimal to binary conversion

## Recommended Posts

O_Joe    122
i was wandering if any1 had some simple code for converting decimal number into binary thanx

##### Share on other sites
Nervo    344
Is this a homework question? Because we all love answering to those kinds of questions.

##### Share on other sites
rossco    103
Divide the decimal value by 2
Store the result
Divide the new decimal value by 2
Until the decimal value equals 0

e.g. 65 / 2 = 32 r 1
32 / 2 = 16 r 0
16 / 2 = 8 r 0
8 / 2 = 4 r 0
4 / 2 = 2 r 0
2 / 2 = 1 r 0
1 / 2 = 0 r 1

Therefore, binary value of 65 is 1000001

Hope that helps my man
I have a function written in C if you want it

What did you think of the Irish beating the English in rugby ?

##### Share on other sites
Guest Anonymous Poster
Oh no, another one of these threads!

<a href="http://www.gamedev.net/community/forums/topic.asp?whichpage=1&pagesize=20&topic_id=212625">See if a number is odd</a>

Okay, let''s here it guys... your best implementation of converting decimal to binary!

Here''s mine: although it only works up to 10

void ConvertDecimalToBinary(int d, char *s) {   switch (d) {      case 0: strcpy(s, "0"); break;      case 1: strcpy(s, "1"); break;      case 2: strcpy(s, "10"); break;      case 3: strcpy(s, "11"); break;      case 4: strcpy(s, "100"); break;      case 5: strcpy(s, "101"); break;      case 6: strcpy(s, "110"); break;      case 7: strcpy(s, "111"); break;      case 8: strcpy(s, "1000"); break;      case 9: strcpy(s, "1001"); break;      case 10: strcpy(s, "1010"); break;   }}

If you want to go higher, just keep adding lines to the switch.

##### Share on other sites
Guest Anonymous Poster
Stupid forum software, how do you get links to work?

http://www.gamedev.net/community/forums/topic.asp?whichpage=1&pagesize=20&topic_id=212625

##### Share on other sites
Agony    3452
I suppose you can''t, if you''re hiding behind a mask of anonymity.

See if a number is odd

##### Share on other sites
Guest Anonymous Poster
quote:
Original post by Anonymous Poster
If you want to go higher, just keep adding lines to the switch.

ROFL!

--cfmdobbie

##### Share on other sites
Guest Anonymous Poster
here it is....
#include <iostream>#include <math.h>#include <string>using namespace std;string Num2Bin(int num){	string ret;	char tmp;	ret = "";	while( num > 0){		itoa((num%2),&tmp,10);		ret += tmp;		num /= 2;	}	return ret;}int main(){	int num;	cout << "Please input a number to convert to a binary string: ";	cin >> num;	cout << Num2Bin(num) << endl;	return 0;}

##### Share on other sites
simba    122
quote:
Original post by Anonymous Poster
here it is....
#include <iostream>#include <math.h>#include <string>using namespace std;string Num2Bin(int num){	string ret;	char tmp;	ret = "";	while( num > 0){		itoa((num%2),&tmp,10);		ret += tmp;		num /= 2;	}	return ret;}int main(){	int num;	cout << "Please input a number to convert to a binary string: ";	cin >> num;	cout << Num2Bin(num) << endl;	return 0;}

As an alternative you could use the right shift operator and mask it which would avoid having to perform the division:

   string Num2Bin( int num ){    unsigned int mask     = 1;    int          bitcount = sizeof( int ) * 8;    char   tmp;    string ret;    ret = "";    for( int i = 0; i < bitcount; i++ )    {        itoa( num & mask, &tmp, 10 );        ret += tmp;        num >> 1;    }    return ret;}

I'm not sure how the string works, so this may give the binary string backwards, but I think that should work. Conversely, I suppose you could left shift the mask instead of right shifting the input value.

[edited by - simba on March 30, 2004 3:22:38 PM]

##### Share on other sites
Guest Anonymous Poster
simba is correct, the string is reversed, here is the mod to reverse the string.
#include <iostream>#include <math.h>#include <string>using namespace std;string reverseStr(string str){	string ret;	int i = str.length();	int j = 0;	ret = str;	while(i--){		ret[j++] = str[i];	}	return ret;}string Num2Bin(int num){	string ret;	char tmp;	ret = "";	while( num > 0){		itoa((num%2),&tmp,10);		ret += tmp;		num >>= 1;  // devide num by 2.	}	//need to reverse the string because it is stored backwards.	return reverseStr(ret);}int main(){	int num;	cout << "Please input a number to convert to a binary string: ";	cin >> num;	cout << Num2Bin(num) << endl;	return 0;}

##### Share on other sites
Guest Anonymous Poster
do you want to find an 8 digit binary number

##### Share on other sites
Guest Anonymous Poster
quote:
Original post by Nervo
Is this a homework question? Because we all love answering to those kinds of questions.

Guys, you''re all doing this wrong. "int" is not a decimal--it''s a machine type (it''s only converted to decimal when you perform the conversion--e.g., when you dump it to a stream).

Here''s how you convert from decimal to binary:

void Convert(char*a,char*b){while(*a&&(!(*a&0xf)))a++;for(char c,d=''0'',e=0,f=a;*a|(c=*a&1);e=c){*a>>=1;*a^=d;*a^=(d>>1);e?*a+=5:0;if(!*++a){Convert(f,b);while(*b)b++;*b=c+d;return;}}}#include <iostream>char* SampleDecimal="125";char BinaryBuffer[50]={0};int main(){Convert(SampleDecimal,BinaryBuffer);std::cout<<BinaryBuffer;}

I believe the code is self documenting.

##### Share on other sites
ms291052    223
Funny, AP, but he''s right, ints are not decimals. O_Joe, I believe the best approach to take would be to store the number as two ints, in a scientific notation type of way, with all the spots to the left of the decimal. For example:

1.35 would be 135(10)^-2 so you could store that as two ints, 135(10000111) and 2(10)(since decimals will always have that negative).

Another example:

3.1415926535897932384626433832795 [somebody check that, I just did that from memory ] would turn in to 31415926535897932384626433832795(10)^-31 so you could save that as 31415926535897932384626433832795 and 31 or their binary forms which are 100011011111100110010001000100010110000011000111011011101011011 and 11111 respectively.

##### Share on other sites
Fruny    1658
#include <bitset>#include <string>using namespace std;template<class T>string tobinary(T decimal){  bitset<sizeof T> tmp(decimal);  return tmp.template to_string<char, char_traits<char>, allocator<char> >();}

##### Share on other sites
Guest Anonymous Poster
quote:
Original post by Anonymous Poster
Guys, you''re all doing this wrong. &quot;int&quot; is not a decimal--it''s a machine type (it''s only converted to decimal when you perform the conversion--e.g., when you dump it to a stream).

Here''s how you convert from decimal to binary:

Oops... copy error. Should be *f=a in the for loop:

void Convert(char*a,char*b){while(*a&&(!(*a&0xf)))a++;for(char c,d=''0'',e=0,*f=a;*a|(c=*a&1);e=c){*a>>=1;*a^=d;*a^=(d>>1);e?*a+=5:0;if(!*++a){Convert(f,b);while(*b)b++;*b=c+d;return;}}}#include <iostream>char* SampleDecimal="125";char BinaryBuffer[50]={0};int main(){Convert(SampleDecimal,BinaryBuffer);std::cout<<BinaryBuffer;}

##### Share on other sites
Zahlman    1682
In the spirit of the is_odd thread:
#define NUMBITS (8 * sizeof (unsigned int))// allocate a new character array containing a binary string represenation of the input integer, and return a pointer thereto.char * decToBin(unsigned int input) {  char sz = NUMBITS;  char * ret = new char[sz];  while(sz) ret[--sz] = '0';  while(input--) {  // can't do this with predecrement unfortunately; then we'd use a do-while loop, but it'd break on input of 0    sz = NUMBITS;    do {      ret[--sz] ^= 1;    } while(sz && (ret[sz] & 1));  }  return ret;}

I think I got that right. Notice how I've tightly optimized the code by use of bitwise operators, predecrements and comparisons against zero rather than the number of iterations.

[edited by - Zahlman on March 31, 2004 3:01:59 AM]

[edited by - Zahlman on March 31, 2004 3:05:03 AM]

##### Share on other sites
Shannon Barber    1681
The x86 (and many other CPUs) has op codes to perform BCD conversions (BCD: Binary Coded Decimal).

##### Share on other sites
Guest Anonymous Poster
just a guess.

#include <limits.h>char *int2binstr(int);int main( void ) { int i = 12323; printf("Binary string: %s\n", int2binstr(i) );}char *int2binstr(int n) { char *str = (char *)malloc( (CHAR_BIT * sizeof(unsigned int)) ); char *ptr = *str; while( (n = n/2) != 0 )  *ptr++ = ( (n&1)==1 ) + 48; *ptr++ = ''\0''; return str;}

##### Share on other sites
Guest Anonymous Poster

##### Share on other sites
Agony    3452
Silly anonymous posters...

12.5 (decimal) -> 1100.1 (binary)

Most of the greatest evils that man has inflicted upon man have come through people feeling quite certain about something which, in fact, was false.

-Bertrand Russell, Unpopular Essays, "Ideas That Have Harmed Mankind"

##### Share on other sites
Zipster    2359
quote:
I believe the code is self documenting.

You know, we don''t fine you for using whitespace. A newline every now and then goes a long way.