User Name Password Register
DaniWeb IT Discussion Community
All
What is DaniWeb IT Discussion Community?
You're currently browsing the C++ section within the Software Development category of DaniWeb, a massive community of 391,921 software developers, web developers, Internet marketers, and tech gurus who are all enthusiastic about making contacts, networking, and learning from each other. In fact, there are 3,688 IT professionals currently interacting right now! Registration is free, only takes a minute and lets you enjoy all of the interactive features of the site.
Please support our C++ advertiser:
Mar 7th, 2007
Views: 4,565
This snippet has a will convert Decimal number to Binary number.
cplusplus Syntax | 5 stars
  1. // coverts decimal to binary
  2. // vishesh
  3. // 21/05/2005
  4.  
  5. #include <iostream>
  6.  
  7. char* DEC_BIN(int);
  8.  
  9. int main()
  10. {
  11. //
  12. int num;
  13. std::cout << "Enter a number: ";
  14. std::cin >> num;
  15. std::cout << DEC_BIN(num);
  16. std::cin.get();
  17. return 0;
  18. }
  19.  
  20. char* DEC_BIN(int dec)
  21. {
  22. using namespace std;
  23.  
  24. char *rtn;
  25.  
  26. int prev, len, temp, *bin;
  27.  
  28. prev = dec;
  29.  
  30. for(int i=0;prev!=0;i++)
  31. {
  32. prev = prev/2;
  33. len=i;
  34. }
  35.  
  36. bin = new int[len+1];
  37.  
  38. prev = dec;
  39.  
  40. for(int i=0;prev!=0;i++)
  41. {
  42. bin[i] = prev%2;
  43. prev = prev/2;
  44. len=i;
  45. }
  46.  
  47. bin[len+1] = prev%2;
  48. len++;
  49.  
  50. for(int i=0;i<len/2;i++)
  51. {
  52. temp=bin[i];
  53. bin[i]=bin[len-1-i];
  54. bin[len-1-i]=temp;
  55. }
  56.  
  57. rtn = new char[len+1];
  58.  
  59. for(int i=0;i<len;i++)
  60. {
  61. rtn[i]=bin[i]+'0';
  62. rtn[i+1]='\0';
  63. }
  64.  
  65. return rtn;
  66. }
Comments (Newest First)
hashjoe | Newbie Poster | Jun 9th, 2008
na na na lot of work :
works in C pretty well :

#include<stdio.h>
main()
{
int i=0,q,num,r[20];
printf("\n\n\nEnter Number\n\n\n");
scanf("%d",&num);
q = num/2;
r[0] = num%2;
while (q>1)
{
q = q/2;
r[i+1] = q%2;
printf("\n\n\n\nbinary is %s\n\n\n",r);
++i;
}
getch();
}
Post Comment

Only community members can submit or comment on code snippets. You must register or log in to contribute.

DaniWeb Marketplace (Sponsored Links)
All times are GMT -4. The time now is 8:11 am.
Forum system based on vBulletin Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
©2003 - 2008 DaniWeb® LLC