The Code-Bin
Links
Home
Add your code!
All Listings
About
Latest Entry
Featured Scripts
Author's Website
Latest Entries
FFMPEG Thumbnail Scr...
PHP, 0.8KB
Jul. 29, 10:24pm
John
Z80 Assembler, 190 bytes
Feb. 17, 3:36am
John
Z80 Assembler, 176 bytes
Sep. 13, 2:19am
John
Z80 Assembler, 77 bytes
Sep. 13, 2:18am
John
Z80 Assembler, 209 bytes
Sep. 13, 2:17am
Dec to bin
Posted by: Aaron | November 19, 2010 @ 7:45pm
C++ Code
[
Download
]
#include <iostream> #include <string> using namespace std; // function returns binary string... even with preceding zeros binary number is still correct. string convertDecimalToBinary(int value); int main() { int x = 0; string s2("NEGATIVE NUMBER EXITING"); cout << "Enter a decimal number (max 524288): "; cin >> x; cout << endl; if(convertDecimalToBinary(x) != s2) { cout << "The number in binary is: " << convertDecimalToBinary(x)<< endl; // call function... } else { cout << s2 << endl; } system("pause"); return 0; } string convertDecimalToBinary(int value) { const int AMOUNT = 20; int one[AMOUNT]; int num_digits(0); int iTemp(0); string s2("NEGATIVE NUMBER EXITING"); iTemp = value; if(iTemp < 0) { return s2; } while(iTemp > 0) { num_digits++; iTemp /= 2; } for(int i = num_digits; i > 0; i--) { one[i] = value % 2; value = value / 2; } string s1; for (int i = 0; i <= num_digits; i++) { if (one[i] == 1) { s1.append("1"); } else if (one[i] == 0) { s1.append("0"); } } return s1; }
Syntax Highlighting
[
Open in new window
]
Author Comments
none
Rating
4.27 / 8
41 Votes
http://codebin.yi.org/970
page generated in 0.00 seconds